JAVA PROGRAMMING LAB MANNUAL
JAVA PROGRAMMING LAB MANNUAL
JAVA PROGRAMMING LAB MANNUAL
- 1-
LABORATORY MANUAL
DEPARTMENT OF
Computer Science and Information
Technology
CERTIFICATE
Vishwavidhyalaya, Bhopal for 3rd Semester of the Computer Science and Information Technology
Signature of
Faculty In-charge
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 3-
DEPARTMENT OF COMPUTER SCIENCE AND
INFORMATION TECHNOLOGY 2024-25
LIST OF EXPERIMENTS
Signature
Expt. Date of
Name of the Experiment of Faculty-in-
No. Conduction
Charge
Write a program that accepts two numbers from the user and
1.
print their sum
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 4-
Experiment No. – 1: Write a program that accepts two numbers from the user and print their sum.
Aim: To understand the concept of Scanner class of java.util Package and the Wrapper classes.
Theory: Since, Java is a pure Object-Oriented Language, it treats everything as a String. So, to accept
numbers (Integers, Float, etc.) from user through keyboard, it is necessary to convert them into numbers
from Strings.
To convert the user input into number, Java provides a Scanner class in java.util Package to convert user
input into numbers from Strings. Following are the methods provided by the Scanner class for conversion:
The second method is to use the Wrapper class of each Primitive data types for performing such conversions.
Various methods of Wrapper classes are as follows:
In order to use the Scanner class, in our Java program, we need to import the Scanner class into our Java
Program, as under:
//To import all classes of Scanner Package, we use the following statement:
import java.util.*;
Next step is to create an Object of Scanner class, as under, in order to facilitate the input through standard
input device.
Scanner S = new Scanner(System.in);
where; S is the object of Scanner class, which will help in accepting user input through standard input
device, such as a keyboard.
System.in instructs the Java compiler to accept user input through standard input device.
Example:
System.out.println("Enter an integer: ");
num = S.nextInt();
System.out.println("Input Integer is: "+num);
Viva Questions:
1. Which Package is needed to import in our Java program to accept user input through standard input
devices?
2. Name the class of util Package that helps us to accept user input through standard input devices.
3. Which method is used to convert user input into Float values?
4. Which method is used to get user input in String?
5. What are Wrapper classes?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 5-
Experiment No. – 2: Write a program to calculate addition of two numbers using prototyping of methods.
Theory:
A function prototype is a function declaration that specifies the data types of its arguments in the parameter
list. The compiler uses the information in a function prototype to ensure that the corresponding function
definition and all corresponding function declarations and calls within the scope of the prototype contain the
correct number of arguments or parameters, and that each argument or parameter is of the correct data type.
Therefore essentially, function prototype specifies the input/output interlace to the function i.e. what to give
to the function and what to expect from the function.
Viva Questions:
1. What do you understand by the term Prototype?
2. Mention a condition, when it is not necessary to give prototype of a function.
3. What happens when a function is called before its declaration?
4. Is it necessary to define names of variables when defining prototypes?
5. How many prototypes have you defined in your program?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 6-
Experiment No. – 3: Write a program to demonstrate function overloading for calculation of average.
Theory: Method Overloading: If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you
write the method such as a(int, int) for two parameters, and b(int, int, int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of the method because its name
differs.
So, we perform method overloading to figure out the program quickly.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 7-
Method Overloading is not possible by changing the return type of the method only.
Viva Questions:
1. What is Method Overloading?
2. Explain the different ways of Method Overloading?
3. Differentiate between Method Overloading and Method Overriding.
4. Can two methods be overloaded, just by changing the return types of the methods?
5. What are the advantages of Method Overloading?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 8-
Experiment No. - 4. Write a program to calculate the volume of Box using the concept of Constructor
Overloading.
Theory:
Constructors :
A Java constructor is special method that is called when an object is instantiated. In other words, when you
use the new keyword. The purpose of a Java constructor is to initializes the newly created object before it is
used.
Syntax:
Following is the syntax of a constructor −
class ClassName {
[<access-modifier>] ClassName() {
}
}
[ ] => Optional
Note: We can use access modifiers while declaring a constructor. It controls the object creation.
In other words, we can have private, protected, public or default constructor.
Difference between constructor and method : Following are the differences between constructors and
methods are:
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 9-
Constructor Overloading
A constructor is just like a method but without a return type. It can also be overloaded like methods.
Constructor overloading is a technique of having more than one constructor with different parameters. They
are arranged in a way that each constructor performs a different task. They are differentiated by the compiler
by the number of parameters and their types.
Viva Questions:
1. What are Constructors?
2. What are the different types of constructor supported by Java?
3. What is the difference between a Default & Parameterized Constructor?
4. What do you understand by Constructor Overloading?
5. What is the difference between a Constructor & a Method?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 10 -
Experiment No. - 5. Write a program to show the details of students using the concept of Inheritance.
Theory:
Inheritance:
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism which one
class inheriting the features (fields and methods) of another class. The class inheriting the features is known
as Derived Class or Sub Class or Child Class. The class whose properties are inherited is own as Base Class
or Super Class or Parent Class.
Types of Inheritance:
1) Single Inheritance: is the simple inheritance of all, when a class extends another class (Only one class)
then we call it as Single inheritance. The below diagram represents the single inheritance where Class B
extends only one class Class A. Here Class B will be the Sub class and Class A will be one and only Super
class.
2) Multilevel Inheritance: In this Inheritance, a derived class will be inheriting a parent class and as well as
the derived class act as the parent class to other class. As seen in the below diagram. Class B inherits the
property of Class A and again Class B act as a parent for Class C. In Short Class A parent for Class B and
Class B parent for Class C.
3) Hierarchical Inheritance: In Hierarchical inheritance one parent class will be inherited by many sub
classes. As per the below example Class A will be inherited by Class B, Class C and Class D. Class A will
be acting as a parent class for Class B, Class C and Class D.
, we have two more inheritance; ie; Multiple and Hybrid which are implements with the help of interface.
Syntax:
Example:
class Employee {
float salary = 40000;
}
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 11 -
class Programmer extends Employee {
int bonus = 10000;
public static void main(String args[]) {
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is:" + p.bonus);
}
}
Viva Questions:
1. What is Inheritance?
2. What are the different types of Inheritance supported by Java?
3. Why multiple inheritance is not supported?
4. What are the other names of a Child Class?
5. Which keyword is used to implement Inheritance?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 12 -
Experiment No. - 6. Write a program to demonstrate the concept of Packages.
Theory:
Java Package: A java package is a group of similar types of classes, interfaces and sub-packages. Package
in java can be categorized in two form, built-
in package and user-defined package. There
are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
How to compile java package: If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name
like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the
same directory, you can use . (dot).
How to run java package program: You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.
Viva Questions:
1. What is a Package?
2. What are the Advantages of Packages?
3. What are Access Specifiers?
4. Which Access Specifier allows outside package accessibility of methods.
5. What is the difference between a Private and Protected Access Specifier.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 13 -
Experiment No. - 7. Write a program to demonstrate implementation of an interface which contains two
methods declaration square and cube
Aim: To understand and implement the concept of Abstract Class & Interface in Java.
Theory:
Abstract Class:
An abstract class is a template definition of methods and variables of a class (category of objects) that
contains one or more abstracted methods. Abstract classes are used in all object-oriented programming (OOP)
languages, including Java.
Example:
abstract class Shape {
abstract void draw();
void disp(){
System.out.println("drawing a shape");
}
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape {
void draw() {
System.out.println("drawing rectangle");
}
}
class Circle extends Shape {
void draw() {
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction {
public static void main(String args[]) {
Shape s = new Rectangle();
Shape s1 = new Circle();
s.disp();
s.draw();
s1.draw();
}
}
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 14 -
Interface:
An interface is just like Java Class, but it only has static constants and abstract method. Java uses Interface to
implement multiple inheritance. A Java class can implement multiple Java Interfaces. All methods in an
interface are implicitly public and abstract.
Example:
interface Pet{
public void test();
}
Viva Questions:
1. What is an Abstract Class?
2. What is an Interface?
3. What is the difference between an Abstract Class & Interface?
4. Which keyword is used to provide implementation of Interface?
5. Which keyword is used to inherit an Abstract Class?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 15 -
Experiment No. – 8. Write a program to demonstrate exception handling in case of division by zero error.
Theory:
Exception Handling:
An exception (or exceptional event) is a problem that arises during the execution of a program. When an
Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications.
JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know how exception
handling works.
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler
at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to
handle the exception.
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs, such as
logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6 th element of the
array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected
code, and the syntax for using try/catch looks like the following −
Syntax:
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
finally{
// finally block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception
occurred is handled by catch block associated with it. Every try block should be immediately followed either
by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 16 -
is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a
method parameter.
Example:
The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three:" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This will produce the following result −
Output
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Viva Questions:
1. What is an Exception?
2. Can we have a try without catch or finally block?
3. What are the different types of Exceptions?
4. Name the base class for various class of Exceptions?
5. Name the block of Exception Handling that executes always whether an Exception is throw or
not.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 17 -
Experiment No. - 9. Write a program to demonstrate Multi-threading.
Theory:
Multithreading is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading,
both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process.
Java Multithreading is mostly used in games, animation, etc.
1. New: The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2. Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
5. Terminated: A thread is in
terminated or dead state when its
run() method exits.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 18 -
Ways to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
3.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed
by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Viva Questions:
1. What is a Thread?
2. What is a Process?
3. What is the difference between a Thread and a Process?
4. What are the ways of creating a Thread?
5. Explain Life Cycle of a Thread.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 19 -
Experiment No. - 10. Write a program to demonstrate the JDBC Concept by creating a GUI based application
for student information.
Theory:
JDBC: JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. It is a part of Java SE (Java Standard Edition). JDBC API uses JDBC drivers to connect
with the database. There are four types of JDBC drivers:
JDBC – ODBC Bridge Driver,
Native – API Driver (partially java driver),
Network Protocol driver (fully java driver),
Thin driver (fully java driver)
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in general,
JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver
manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the
JDBC drivers and the Java application –
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 20 -
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages: Disadvantages:
Easy to use. Performance degraded because JDBC
Can be easily connected to any database. method call is converted into the ODBC
function calls.
The ODBC driver needs to be installed on
the client machine.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 21 -
3) Network Protocol driver (fully java driver):
The JDBC type 3 driver, also known as the Pure Java driver for database middleware, is a database driver
implementation which makes use of a middle tier between the calling program and the database. The middle-
tier (application server) converts JDBC calls directly or indirectly into a vendor-specific database protocol.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 22 -
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in
the classpath, and then JDBC driver manager can detect and load the driver automatically.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 23 -
Example to close connection
con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.
Viva Questions:
1. What is JDBC?
2. Explain the different types of JDBC Drivers?
3. Differentiate between Type – 3 and Type – 4 Drivers.
4. Illustrate the steps involved in JDBC Connectivity.
5. Explain the different controls used in the JFrame.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 24 -
Experiment No. - 11. Write a program to display “Hello World” in web Browser using Applet.
Theory:
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantages: Disadvantages:
It works at client side so less response time. Plugin is required at client browser to
Secured execute applet.
It can be executed by browsers running under
many platform’s, including Linux,
Windows, Mac OS etc.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class:
For creating any applet java.applet.Applet class must
be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the
Applet. It is invoked only once.
2. public void start(): is invoked after the init()
method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet.
It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the
Applet. It is invoked only once. Figure 11.1: Life Cycle of Applet
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 25 -
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on the
browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300"></applet>
</body>
</html>
c:\>javac First.java
c:\>appletviewer First.java
Viva Questions:
1. What is an Applet?
2. Explain Life Cycle of an Applet.
3. Which JDK tool is used to run an Applet? Explain its Syntax.
4. Explain Life Cycle methods of an Applet.
5. Which attribute is used to execute an Applet through JDK Tool?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 26 -
Experiment No. – 12. Write a program to add user controls to applets.
Theory:
Java AWT: Abstract Window Toolkit is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
Window: The window is the container that have no borders and menu
bars. You must use frame, dialog or another window for creating a
window.
Panel: The Panel is the container that doesn't contain title bar and menu
bars. It can have other components like button, textfield etc.
Frame: The Frame is the container that contain title bar and can have
menu bars. It can have other components like button, textfield etc
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 27 -
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>
Viva Questions:
1. What is an Event?
2. Name some of the events that you have studied.
3. What is the actionPerformed() method?
4. What is setText() method?
5. What is SetBounds() method?
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 28 -
Experiment No. - 13. Write a program to create an application using the concept of Swing.
Theory:
JLabel: The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.
JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and
int horizontalAlignment) horizontal alignment.
Table 13.1: Commonly used Constructors of JLable Class
Methods Description
String getText() It returns the text string that a label show.
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.
Table13.2: Commonly used Methods of JLabel Class
JComboBox: The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Action
Listener, Accessible
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified
array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the specified
items) Vector.
Table 13.3: Commonly used Constructors of JComboBox Class
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 29 -
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the AtionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
Table 13.4: Commonly used Methods of JComboBox Class
Viva Questions:
1. Compare AWT and Swings.
2. Compare TextField and TextArea.
3. What is SetBounds() method? How many parameters does it take?
4. Which component is used to display a message to a user?
5. Name the component used to accept input from user at runtime.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 30 -
Experiment No. - 14. Program to demonstrate student registration functionality using servlets with session
management.
Aim: To understand the concept of Web Programming and creating HTML Form and process the same on the
server and saving the data to database.
Theory:
HTML: HTML stands for Hyper Text Markup Language. It is used to design web pages using markup
language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between
the web pages. Markup language is used to define the text document within tag which defines the structure of
web pages. This language is used to annotate (make notes for the computer) text so that a machine can
understand it and manipulate text accordingly. Most of markup (e.g. HTML) languages are human readable.
Language uses
tags to define what manipulation has to be done on the text.
HTML is a markup language which is used by the browser to manipulate text, images and other content to
display it in required format. HTML was created by Tim Berners-Lee in 1991. The first ever version of HTML
was HTML 1.0 but the first standard version was HTML 2.0 which was published in 1999.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 31 -
Servlets vs CGI:
Basis for
CGI Servlet
comparison
Basic Programs are written in the native OS. Programs employed using Java.
Platform Platform dependent Does not rely on the platform
dependency
Creation of Each client request creates its own Processes are created depending on
process process. the type of the client request.
Conversion of Present in the form of executables Compiled to Java Bytecode.
the script (native to the server OS).
Runs on Separate process JVM
Security More vulnerable to attacks. Can resist attacks.
Speed Slower Faster
Processing of Direct Before running the scripts it is
script translated and compiled.
Portability Can’t be ported Portable
Table 14.1: Servlets vs CGI
The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 32 -
Cookies in Servlet:
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional
attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 34 -
2. Persistent cookie: It is valid for multiple session. It is not removed each time when user closes the
browser. It is removed only if user logout or sign-out.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Viva Questions:
1. What are Servlets? What are its advantages?
2. What is a Session? What are the methods used for Session Tracking? Explain any 1.
3. Explain the Servlet Life Cycle. Explain its various methods.
4. Which method is used to retrieve Parameters?
5. What are Cookies? Explain its advantages & Disadvantages
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY