JAVA PROGRAMMING LAB MANNUAL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

JAVA PROGRAMMING LAB

- 1-

LABORATORY MANUAL

JAVA PROGRAMMING LAB


(CSIT - 306)

III SEM (CSIT)

DEPARTMENT OF COMPUTER SCIENCE AND


INFORMATION TECHNOLOGY
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 2-

CHAMELI DEVI GROUP OF INSTITUTIONS


INDORE (M.P.)

DEPARTMENT OF
Computer Science and Information
Technology

CERTIFICATE

This is to certify that Mr./Ms with

RGTU Enrollment No. has satisfactorily completed the course of experiments

CSIT-306; Java Programming Lab laboratory, as prescribed by Rajiv Gandhi Proudhyogiki

Vishwavidhyalaya, Bhopal for 3rd Semester of the Computer Science and Information Technology

Department during year 2024– 25.

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

Write a program to calculate addition of two number using


2.
prototyping of methods.

Write a program to demonstrate function overloading for


3.
calculation of average.

Write a program to perform calculate the volume of Box using


4.
the concept of Constructor Overloading.

Write a program to show the detail of students using concept of


5.
inheritance.

6. WAP to demonstrate the concept of Packages.

Write a program to demonstrate implementation of an interface


7.
which contains two methods declaration square and cube.

Write a program to demonstrate exception handling in case of


8.
division by zero error.

9. Write a program to demonstrate multithreading.

Write a program to demonstrate JDBC concept using create a


10.
GUI based application for student information.

Write a program to display “Hello World” in web browser using


11.
applet.

12. Write a program to add user controls to applets.

Write a program to create an application using concept of


13.
swing.

Program to demonstrate student registration functionality using


14.
servlets with session management.

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:

i. public String nextLine(): For String input


ii. public int nextInt(): For integer input
iii. public float nextFloat(): For float input
iv. public double nextDouble(): For double input

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:

i. Integer.parseInt(s); for Conversion to Integer values


ii. Float.parseFloat(s); for Conversion to Float values

In order to use the Scanner class, in our Java program, we need to import the Scanner class into our Java
Program, as under:

//This shall import only Scanner class of util Package:


import java.util.Scanner;

//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.

Aim: To understand the importance of prototypes.

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.

The Function prototype serves the following purposes –


1. It tells the return type of the data that the function will return.
2. It tells the number of arguments passed to the function.
3. It tells the data types of the each of the passed arguments.
4. Also, it tells the order in which the arguments are passed to the function.

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.

Prototype of a function is also called signature of the function.

Some Examples of Prototypes are:

1. void add(int, float);


This prototype tells the compiler that, the add function will take 2 parameters and it will not return any
value.

2. float area(int, int);


This prototype tells the compiler that, the area function will take 2 parameters and it will return a float type
value.

3. int LSearch(int [], int, int);


This prototype tells the compiler that, the LSearch function will take 3 parameters out of which 1 is an Array
and it will return a integer type value.

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.

Aim: To understand and implement the concept of method overloading

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.

Advantage of Method Overloading:


 Method overloading increases the readability of the program.

Different ways to overload the method:


There are two ways to overload the method
1. By changing number of arguments:
Example:
class Adder{
int add(int a, int b){
return a+b;
}
int add(int a, int b, int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
Adder A = new Adder();
System.out.println(A.add(11,11));
System.out.println(A.add(11,11,11));
}
}

2. By changing the data types:


Example:
class Adder{
int add(int a, int b){
return a + b;
}
int add(float a, int b, float c){
return a + b + c;
}
}
class TestOverloading1{
public static void main(String[] args){
Adder A = new Adder();
System.out.println(A.add(11,11));
System.out.println(A.add(11.5,12,13.5));
}
}

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.

Aim: To understand and implement 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

Rules for creating Java constructor:


The rules for defining the constructor are:
1. Constructor name must be the same as its class name.
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

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.

Types of Java constructors


There are two types of constructors:
1. Default constructor (no-args constructor)
2. Parameterized constructor

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Difference between constructor and method : Following are the differences between constructors and
methods are:

Java Constructor Java Method


A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default The method is not provided by the compiler in any
constructor if you don't have any constructor in case.
a class.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.

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.

Constructor Overloading Example:

//Java program to overload constructors


class Student {
int id;
String name;
int age;
//creating two arg constructor
Student(int i, String n) {
id = i;
name = n;
}
//creating three arg constructor
Student(int i, String n, int a) {
id = i;
name = n;
age = a;
}
void display() {
System.out.println(id + " " + name + " " + age);
}
public static void main(String args[]) {
Student s1 = new Student(111, "Karan");
Student s2 = new Student(222, "Aryan", 25);
s1.display();
s2.display();
}
}

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.

Aim: To understand and implement 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.

Terms used in Inheritance:


 Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
 Sub Class/Child Class/Derived Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
 Super Class/Parent Class/Base Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class. 
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous 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:

class Subclass-name extends Superclass-name


{
//methods and fields
}

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.

Aim: To understand and implement the concept of Packages in Java.

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.

Advantage of Java Package:


1) Java package is used to categorize the
classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java. Figure-6.1: Packages
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

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.

Syntax for Declaring Abstract Class:


abstract class <class-name>{
//body of class
}
Individual instances resulting from classes are objects. Declaring a class as abstract means that it cannot be
directly instantiated, which means that an object cannot be created from it. That protects the code from being
used incorrectly.
To use an abstract class in your class, append the keyword "extends" after your class name followed by the
abstract class name.

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.

Syntax for Declaring Interface:


interface <interface-name>{
//methods & variables
}
To use an interface in your class, append the keyword "implements" after your class name followed by the
interface name.

Example:
interface Pet{
public void test();
}

class Dog implements Pet{


public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.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.

Aim: To understand and implement the concept of Exception Handling in Java.

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

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following −
Syntax:
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch 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.

Aim: To understand and to implement the concept of Multi-threading in Java.

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.

Advantages of Java Multithreading:


1. It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Life cycle of a Thread:


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle new,
runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread is controlled by JVM. The java thread states are as follows:

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.

3. Running: The thread is in


running state if the thread
scheduler has selected it.

4. Non-Runnable (Blocked): This


is the state when the thread is still
alive, but is currently not eligible
to run.

5. Terminated: A thread is in
terminated or dead state when its
run() method exits.

Figure-9.1: Life Cycle of a Thread

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.

1. Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...

2. Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

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.

Aim: To perform CRUD operations using AWT / Swings.

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 –

The current version of JDBC is 4.3. It is the stable


release since 21st September, 2017. The java.sql and
javax.sql package contains classes and interfaces for
JDBC API.

A list of popular interfaces of JDBC API are given


below:
 Driver interface 
 Connection interface
 Statement interface
 PreparedStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
Figure-10.1: JDBC Architecture
A list of popular classes of JDBC API are given below:
 DriverManager class

Types of JDBC Drivers:


1) JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.

CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 20 -

Figure – 10.2: JDBC – ODBC Bridge Driver

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.

2) Native – API Driver (partially java driver):


The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that
uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the
database API.
Advantages: Disadvantages:
 performance upgraded than JDBC-ODBC  The Native driver needs to be installed on
bridge driver. each client machine.
 The Vendor client library needs to be
installed on client machine.

Figure – 10.3: Native API Driver

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.

Figure – 10.4: Network Protocol driver


Advantages: Disadvantages:
 No client-side library is required because of  Network support is required on client
application server; that can perform many machine.
tasks like auditing, load balancing, logging  Requires database-specific coding to be done
etc. in the middle tier.
 Maintenance of Network Protocol driver
becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver (fully java driver):


The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver
implementation that converts JDBC calls directly into a vendor-specific database protocol.
Written completely in Java, type 4 drivers are thus platform independent. They install inside the Java Virtual
Machine of the client. This provides better performance than the type 1 and type 2 drivers as it does not have
the overhead of conversion of calls into ODBC or database API calls. Unlike the type 3 drivers, it does not
need associated software to work.

Figure – 10.5: Thin Driver


Advantages: Disadvantages:
 Better performance than all other drivers.  Drivers depend on the Database.
 No software is required at client side or
server side.

Java Database Connectivity Steps:


There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:

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

1) Register the driver class:


The forName() method of Class class is used to register the driver class. This method is used to dynamically
load the driver class.
Syntax of forName() method:
public static void forName(String className)throws ClassNotFoundException

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.

Example to register the Oracle Driver class


Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object:


The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection()method
1. public static Connection getConnection(String url)throws SQLException
2. public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database:
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","passw
ord");

3) Create the Statement object:


The createStatement() method of Connection interface is used to create statement. The object of statement is
responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

4) Execute the Query:


The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
5) Close the connection object:
By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException

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.

Database MetaData Interface:


DatabaseMetaData interface provides methods to get meta data of a database such as database product name,
database product version, driver name, name of total number of tables, name of total number of views etc.
Commonly used methods of DatabaseMetaData interface are:
 public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
 public String getDriverVersion()throws SQLException: it returns the version number of the JDBC
driver.
 public String getUserName()throws SQLException: it returns the username of the database.
 public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
 public String getDatabaseProductVersion()throws SQLException: it returns the product version
of the database.
 public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified catalog.
The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:


The getMetaData() method of Connection interface returns the object of DatabaseMetaData.
Syntax:
public DatabaseMetaData getMetaData()throws SQLException

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.

Aim: To understand and implement the concepts of Applets.

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.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and
java.awt.Component class provides 1 life cycle
methods for an applet.

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.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletviewer tool.

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>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile
it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*<applet code="First.class" width="300" height="300"></applet>
*/

To execute the applet by appletviewer tool, write in command prompt:

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.

Aim: To perform event handling in 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.

Container: The Container is a component in AWT that can contain


another components like buttons, textfields, labels etc. The classes that
extends Container class are known as container such as Frame, Dialog
and Panel.

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

Event Handling in Applet: As we perform event handling in AWT or


Swing, we can perform it in applet also. Let's see the simple example of event handling in applet that prints
a message by click on the button.

Example of EventHandling in applet:


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}

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.

Aim: To create a GUI application using Swings in Java

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 class declaration


Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string
for the title.
JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

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.

Some of the tags used in HTML are:


<!DOCTYPE>: It defines the document type or it instruct the browser about the version of HTML.
<html >: This tag informs the browser that it is an HTML document. Text between html tag describes the web
document. It is a container for all other elements of HTML except <!DOCTYPE>
<head>: It should be the first element inside the <html> element, which contains the metadata (information
about the document). It must be closed before the body tag opens.
<title>: As its name suggested, it is used to add title of that HTML page which appears at the top of the
browser window. It must be placed inside the head tag and should close immediately.
<body>: Text between body tag describes the body content of the page that is visible to the end user. This tag
contains the main content of the HTML document.
<h1>: Text between <h1> tag describes the first level heading of the webpage.
<p>: Text between <p> tag describes the paragraph of the webpage.

What is a web application?


A web application is an application accessible from the web. A web application is composed of web
components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and respond to the HTTP request.

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request
coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database or
another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface
(CGI). But Servlets offer several advantages in comparison with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine. So, servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can communicate with
applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 31 -

Figure 14.1: Client Server Architecture

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 -

Figure 14.2: Processing Client’s Request by CGI & Servlet

Life Cycle of a Servlet:


The web container maintains the life cycle of a
servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the diagram, there are three states of


a servlet: new, ready and end. The servlet is in new
state if servlet instance is created. After invoking the
init() method, Servlet comes in the ready state. In the
ready state, servlet performs all the tasks. When the
web container invokes the destroy() method, it shifts
to the end state.

A Simple Servlet Example: Figure 14.3: Servlet Life Cycle


Following is the sample source code structure of a servlet example to show Hello World −

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException {

// Set response content type


response.setContentType("text/html");
CHAMELI DEVI GROUP OF INSTITUTIONS, INDORE. DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
JAVA PROGRAMMING LAB
- 33 -

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}

Session Tracking in Servlets:


Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of a user. It is also known as session management in
servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user
requests to the server, server treats the request as the new request. So, we need to maintain the state of a user
to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given
below:

Why use Session Tracking?


HTTP is a "stateless" protocol which means each time a client retrieves a Web page; the client opens a separate
connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server −

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

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.

How Cookie works


By default, each request is considered as a new
request. In cookies technique, we add cookie with
response from the servlet. So, cookie is stored in
the cache of the browser. After that if request is
sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old
user.

Types of Cookie: Figure 14.4: Working of a Cookie


There are 2 types of cookies in servlets.
1. Non-persistent cookie: It is valid for single session only. It is removed each time when user closes
the browser.

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

You might also like