0% found this document useful (0 votes)
3 views81 pages

Java Lab Manual Improved

The JAVA LAB MANUAL outlines a series of experiments focused on Object Oriented Programming using Java, including basic arithmetic operations, method overloading, and exception handling. Each experiment includes aims, prerequisites, outcomes, and theoretical background, providing students with practical programming experience. The manual emphasizes the importance of concepts like the Scanner class, modular programming, and compile-time polymorphism in developing Java applications.

Uploaded by

kunalpatil29th
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views81 pages

Java Lab Manual Improved

The JAVA LAB MANUAL outlines a series of experiments focused on Object Oriented Programming using Java, including basic arithmetic operations, method overloading, and exception handling. Each experiment includes aims, prerequisites, outcomes, and theoretical background, providing students with practical programming experience. The manual emphasizes the importance of concepts like the Scanner class, modular programming, and compile-time polymorphism in developing Java applications.

Uploaded by

kunalpatil29th
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA LAB MANUAL

Object Oriented Programming Using Java

Exp. Experiment Title


No.
1 Write a program that accepts two numbers from the user and print their sum.

2 Write a program to calculate addition of two numbers using prototyping of


methods.
3 Program to demonstrate function overloading for calculation of average.

4 Program to demonstrate overloaded constructor for calculating box volume.

5 Program to show the detail of students using concept of inheritance.

6 Program to demonstrate package concept.

7 Program to demonstrate implementation of an interface which contains two


method declarations square() and cube().
8 Program to demonstrate exception handling in case of division by zero error.

9 Program to demonstrate multithreading.

10 Program to demonstrate JDBC concept using a GUI-based application for


student information.
11 Program to display "Hello World" in web browser using applet.

12 Program to add user controls to applets.

13 Program to create an application using concept of Swing.

14 Program to demonstrate student registration functionality using Servlets with


Session Management.
Experiment No. 1

PART A

A.1 Aim:
To study and implement the concept of basic input/output and arithmetic operations in
Java programming language and understand its practical use in software development.

A.2 Prerequisite:
Before performing this experiment, students should have knowledge of:

 Basic computer programming concepts


 Java program structure
 Variables and data types in Java
 Arithmetic operators
 Input and output operations
 Usage of Scanner class
 Compilation and execution of Java programs

A.3 Outcome:
After successful completion of this experiment, students will be able to:

1. Understand the basic structure of a Java program.


2. Accept data from the user using the Scanner class.
3. Perform arithmetic operations using Java operators.
4. Display formatted output on the console.
5. Develop simple interactive Java applications.
6. Apply programming logic to solve numerical problems.

A.4 Theory:
Java is a high-level, object-oriented, platform-independent programming language
developed by Sun Microsystems (now Oracle Corporation). It follows the principle of
"Write Once, Run Anywhere" (WORA), meaning that Java programs can run on any
platform that supports the Java Virtual Machine (JVM).

One of the most important aspects of programming is the ability to accept input from
users and process it to generate meaningful output. In Java, user input can be accepted
using the Scanner class available in the [Link] package.

A variable is a named memory location used to store data values. In this experiment,
integer variables are used to store the two numbers entered by the user.

Arithmetic operators are used to perform mathematical calculations. The addition


operator (+) adds two operands and returns their sum.
The program begins execution from the main() method, which serves as the entry point
of every Java application. The Scanner object is created to read input from the keyboard.
The entered values are stored in variables, added together, and the result is displayed on
the screen.

This experiment introduces students to the basic programming cycle:

Input → Processing → Output

The concept learned in this experiment forms the foundation for more advanced
programming tasks such as calculations, data processing, database operations, and
software development.

Task 1:
Analyze the role of the Scanner class and identify how user input is received and stored
in variables.

Task 2:
Modify the program to calculate the sum of three numbers instead of two and identify the
changes required in the code.
Experiment No. 1

PART B

Roll No. 0818CL241108 Name : Kunal Patil


Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code written by student:


import [Link];

public class SumOfTwoNumbers {


public static void main(String[] args) {

[Link]("Name: Kunal Patil");


[Link]("Roll No.: 0818CL241108");

Scanner sc = new Scanner([Link]);

[Link]("Enter first number: ");


int num1 = [Link]();

[Link]("Enter second number: ");


int num2 = [Link]();

int sum = num1 + num2;

[Link]("Sum of two numbers = " + sum);

[Link]();
}
}

B.2 Input and Output:


B.3 Observations and Learning:
During the execution of the program, it was observed that Java accepts user input through
the Scanner class and stores it in memory using variables. The entered values were
successfully processed using the addition operator, and the correct result was displayed
on the console.

Students observed that:

 Variables store user-provided data temporarily during program execution.


 The Scanner class simplifies keyboard input operations.
 Arithmetic operators can be used to perform calculations efficiently.
 Program execution follows a sequential flow.
 Proper declaration and initialization of variables are necessary for correct program
execution.

The experiment enhanced understanding of input-output operations and arithmetic


processing in Java. It also strengthened logical thinking and programming fundamentals.

B.4 Conclusion:
From this experiment, it can be concluded that Java provides simple and effective
mechanisms for accepting user input and performing arithmetic calculations. The Scanner
class enables interaction between the user and the program, while arithmetic operators
facilitate data processing.

The experiment helped students understand the basic structure of Java programs, variable
handling, and console-based interaction. These concepts serve as the foundation for
developing more complex software applications. Students gained confidence in writing,
compiling, and executing Java programs.

B.5 Question of Curiosity:

 Why is the Scanner class required for taking input from the user?
Answer:
The Scanner class is used to take input from the keyboard.
It reads data entered by the user during program execution.
The input is stored in variables for processing.
It supports different data types like int, float, and String.
It makes Java programs interactive and user-friendly.

 What is the difference between int, float, and double data types?
Answer:
int is used to store whole numbers without decimals.
float stores decimal numbers with single precision.
double stores decimal numbers with higher precision than float.
double is more accurate for calculations involving decimals.
The choice depends on the type of data being stored.

 What happens if a user enters a character instead of a number?


Answer:
If a character is entered instead of a number, Java cannot convert it.
The program throws an InputMismatchException.
This causes the program to stop unless the exception is handled.
Input validation can prevent such errors.
Exception handling improves program reliability.

 Can the program be modified to add more than two numbers? How?
Answer
Yes, the program can be modified to add more numbers.
Create additional variables for the extra inputs.
Use the Scanner class to read each number.
Add all the numbers using the + operator.
Display the final sum on the console.

 What are some real-world applications where user input is required?


Answer:
User input is required in ATM machines for transactions.
It is used in online banking and shopping websites.
Student and hospital management systems also take user input.
Login and registration forms require user details.
Many desktop and mobile applications depend on user input.
Experiment No. 2

PART A

A.1 Aim
To write a program to calculate the addition of two numbers using prototyping of
methods.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Basic Java program structure


 Variables and data types
 Arithmetic operators
 Classes and objects
 Input and output operations
 Fundamentals of functions/methods
 Compilation and execution of Java programs

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of methods in Java.


2. Declare and define methods with parameters and return values.
3. Invoke methods using objects.
4. Develop modular and reusable Java programs.
5. Improve code readability and maintainability.
6. Apply methods to solve programming problems efficiently.

A.4 Theory

A method is a collection of statements that performs a specific task. Methods help


programmers divide large programs into smaller, manageable, and reusable modules.
This approach is known as modular programming.

In Java, methods can accept data through parameters, process the data, and optionally
return a result. A method generally consists of:

 Return Type
 Method Name
 Parameter List
 Method Body
General syntax:

returnType methodName(parameters)

{ // statements

Methods provide several advantages:

1. Code Reusability :A method can be called multiple times from different parts of the
program without rewriting the same code.

2. Reduced Complexity :Large programs become easier to understand when divided into
smaller methods.

3. Easy Maintenance :Changes made in a method automatically affect all places where it
is called.

4. Better Debugging:Errors can be identified and corrected more easily within a method.

In this experiment, a method named add() is created to perform the addition of two
numbers. The numbers are passed as arguments to the method. The method calculates
their sum and returns the result to the calling statement.

The execution flow of the program is:

Main Method → Method Call → Processing → Return Value → Output

This experiment demonstrates how methods improve program organization and prepare
students for advanced concepts such as function overloading, recursion, inheritance, and
object-oriented software development.

Methods are extensively used in real-world software applications, including banking


systems, e-commerce platforms, operating systems, mobile applications, and enterprise
software.

Task 1

Analyze the role of parameters and return values in the add() method and explain how
data is transferred between the calling method and the called method.

Task 2

Modify the program to perform subtraction, multiplication, and division using separate
methods and compare the structure of the program with the original version.
Experiment No. 2
PART B

Roll No : Kunal Patil Name : 0818CL241108


Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code written by student:

public class AdditionUsingMethod {

int add(int num1, int num2) {


int sum = num1 + num2;
return sum;
}

public static void main(String[] args) {

[Link]("Name: Kunal Patil");


[Link]("Roll No.: 0818CL241108");

AdditionUsingMethod obj = new AdditionUsingMethod();

int result = [Link](25, 15);

[Link]("Addition = " + result);


}
}

B.2 Input and Output


B.3 Observations and Learning

During the execution of the program, it was observed that the addition operation was
performed inside a separate method rather than directly within the main() method. The
values passed as arguments were successfully received by the method through
parameters, processed internally, and the result was returned to the calling statement.

Students observed that:

 Methods help divide programs into smaller logical units.


 Parameters allow data to be passed to a method.
 Return statements send processed results back to the calling method.
 Method invocation enables code reuse.
 Modular programming improves readability and maintainability.
 Changes can be made in one method without affecting the overall structure of the
program.

The experiment provided practical exposure to the concept of methods and demonstrated
how software developers use methods to organize large applications efficiently.

B.4 Conclusion

From this experiment, it can be concluded that methods are one of the most important
building blocks of Java programming. They help organize programs into reusable and
manageable components, reducing redundancy and improving program structure.

The experiment successfully demonstrated method declaration, method invocation,


parameter passing, and return values. Students gained practical knowledge of modular
programming and understood how methods contribute to software development by
improving code quality, maintainability, scalability, and reusability.

The knowledge gained from this experiment serves as a foundation for advanced Java
concepts such as function overloading, recursion, interfaces, and object-oriented
application development.

B.5 Questions of Curiosity

1. What is the difference between a method parameter and an argument?

Answer:
A parameter is a variable declared in a method definition.
An argument is the actual value passed to the method.
Parameters receive the values from arguments.
They help methods process different inputs.
Both are essential for method execution.
2. Why is a return statement important in a method?

Answer:
The return statement sends a value back to the calling method.
It ends the execution of the method.
The returned value can be used in further calculations.
It makes methods more useful and reusable.
It improves program efficiency.

3. Can a method return multiple values? If yes, how?

Answer:
A method cannot return multiple values directly.
It can return an array or an object containing multiple values.
Another way is to use a collection like ArrayList.
These methods allow multiple values to be accessed together.
This improves data organization.

4. What is the difference between a method with a return type and a void method?

Answer:
A method with a return type returns a value.
A void method does not return any value.
The return type is specified before the method name.
A void method performs a task only.
Both methods are useful for different purposes.

5. How do methods improve software maintenance in large applications?

Answer:
Methods divide a program into smaller modules.
They reduce code duplication.
Changes are made in one place only.
Debugging becomes easier and faster.
This makes software easier to maintain.

6. Where are methods commonly used in real-world software systems?

Answer:
Methods are used in banking applications.
They are used in e-commerce websites.
Mobile and desktop applications use methods extensively.
Hospital and student management systems also use methods.
Methods are essential in almost every software application
Experiment No. 3
PART A

A.1 Aim

To write a program to demonstrate function overloading for calculation of average.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Classes and objects


 Methods in Java
 Parameters and return values
 Arithmetic operators
 Basic Object-Oriented Programming concepts
 Method calling and object creation

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of function overloading in Java.


2. Differentiate between overloaded methods based on parameter lists.
3. Implement multiple methods with the same name for different requirements.
4. Calculate averages using overloaded methods.
5. Improve code readability and flexibility through method overloading.
6. Apply compile-time polymorphism in Java programs.

A.4 Theory

Function overloading, also known as Method Overloading, is one of the important


features of Object-Oriented Programming in Java. It allows multiple methods within the
same class to have the same name but different parameter lists.

Method overloading is an example of Compile-Time Polymorphism or Static


Polymorphism because the method to be executed is determined by the compiler during
compilation.

In Java, methods can be overloaded by changing:

 Number of parameters
 Data type of parameters
 Order of parameters

However, methods cannot be overloaded solely by changing the return type.


Why Method Overloading is Needed

Method overloading improves:

1. Readability : Instead of creating different method names for similar operations, a


single method name can be used.

Example:

average(10,20)
average(10,20,30)

Both methods perform average calculations but accept different numbers of parameters.

2. Code Reusability :Developers can use the same method name for related operations,
making programs easier to understand and maintain.

3. Flexibility :The same operation can be performed on different types or amounts of


data.

Working of Method Overloading

When an overloaded method is called, the compiler checks:

 Method name
 Number of arguments
 Data type of arguments

Based on these factors, the compiler determines which version of the method should be
executed.

Advantages of Method Overloading

 Improves code readability.


 Reduces the need for multiple method names.
 Makes programs easier to maintain.
 Supports compile-time polymorphism.
 Enhances software flexibility.

Applications of Method Overloading

Method overloading is commonly used in:

 Mathematical calculations
 Banking applications
 Scientific software
 Calculator programs
 Enterprise applications
 API development

In this experiment, two methods named average() are created. One method calculates the
average of two numbers, while the other calculates the average of three numbers. The
compiler automatically selects the appropriate method based on the arguments supplied.

Thus, this experiment demonstrates how Java supports method overloading and how it
simplifies software development.

Task 1

Analyze how the Java compiler differentiates between overloaded methods and identify
the parameter list used for each method call.

Task 2

Modify the program by creating another overloaded method to calculate the average of
four numbers and explain the changes required.
PART B
Roll No : 0818CL241108 Name: Kunal Patil
Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


class Average {

double average(int a, int b) {

return (a + b) / 2.0;

double average(int a, int b, int c) {

return (a + b + c) / 3.0;

public static void main(String[] args) {

[Link]("Name: Kunal Patil");

[Link]("Roll No.: 0818CL241108");

Average obj = new Average();

[Link]("Average of 2 numbers = " + [Link](10, 20));

[Link]("Average of 3 numbers = " + [Link](10, 20, 30));

}
B.2 Input and Output

B.3 Observations and Learning

During the execution of the program, it was observed that Java allows multiple methods
having the same name within the same class provided their parameter lists are different.
The compiler successfully identified the appropriate method based on the number of
arguments supplied during method invocation.

Students observed that:

 Methods can have the same name with different parameter lists.
 The compiler selects the correct method during compilation.
 Method overloading simplifies program design.
 A single operation can be implemented for different input requirements.
 Code becomes more readable and maintainable.

The experiment demonstrated the practical implementation of compile-time


polymorphism and showed how overloaded methods reduce complexity in software
development. Students gained a clear understanding of how Java resolves method calls
and executes the appropriate method.

B.4 Conclusion

From this experiment, it can be concluded that method overloading is a powerful feature
of Java that enables multiple methods with the same name to perform related tasks. It
improves code readability, maintainability, and flexibility by allowing a single method
name to handle different parameter combinations.

Students successfully learned how compile-time polymorphism works and how


overloaded methods can be used to solve similar problems efficiently. The concept is
widely used in real-world software systems to develop scalable and user-friendly
applications.

The experiment enhanced programming skills, logical thinking, and understanding of


object-oriented programming concepts.
B.5 Questions of Curiosity

1. What is method overloading in Java?

Answer:
Method overloading means having multiple methods with the same name.
The methods must have different parameter lists.
It allows the same operation for different inputs.
It improves code readability and flexibility.
It is a feature of object-oriented programming.

2. Why is method overloading called compile-time polymorphism?

Answer:
The compiler decides which method to call during compilation.
The decision is based on the parameter list.
No decision is made during program execution.
Therefore, it is called compile-time polymorphism.
It is also known as static polymorphism

3. Can methods be overloaded by changing only the return type? Why?

Answer:
No, methods cannot be overloaded by changing only the return type.
The parameter list must be different.
The compiler ignores the return type when selecting methods.
Changing only the return type causes a compilation error.
Therefore, parameter changes are necessary.

4. How does the compiler decide which overloaded method to execute?

Answer:
The compiler checks the method name.
It compares the number of arguments passed.
It also checks the data types of the arguments.
Then it selects the matching method.
This selection happens during compilation.
5. What are the advantages of method overloading in software development

Answer:
Method overloading improves code readability.
It reduces the need for multiple method names.
It increases code reusability.
It makes programs easier to maintain.
It provides flexibility in handling different inputs.

Experiment No. 4
PART A

A.1 Aim

To write a program demonstrating overloaded constructors for calculating box


volume.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Instance variables
 Methods in Java
 Constructors
 Parameter passing
 Object-Oriented Programming fundamentals
A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of constructors in Java.


2. Differentiate between default and parameterized constructors.
3. Implement constructor overloading in Java programs.
4. Initialize objects using different constructors.
5. Calculate box volume using object-oriented techniques.
6. Apply constructor overloading for flexible object creation.

A.4 Theory

A constructor is a special member of a class that is automatically invoked whenever an


object of the class is created. Its primary purpose is to initialize the data members of the
object.

A constructor has the same name as the class and does not have any return type, not even
void.

Characteristics of Constructors

 Called automatically when an object is created.


 Used to initialize instance variables.
 Has the same name as the class.
 Does not return any value.
 Can be overloaded.

Types of Constructors

1. Default Constructor

A constructor that does not accept any arguments.

Example:

Box() {
length = breadth = height = 1;
}
2. Parameterized Constructor

A constructor that accepts arguments to initialize object values.

Example:
Box(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}

Constructor Overloading

When a class contains more than one constructor with different parameter lists, it is
called Constructor Overloading.

Constructor overloading allows objects to be initialized in different ways depending on


the requirements of the program.

Example:

Box box1 = new Box();

Box box2 = new Box(2, 3, 4);

In the above example:

 box1 uses the default constructor.


 box2 uses the parameterized constructor.

Why Constructor Overloading is Needed

1. Flexibility :Objects can be initialized using different sets of values.

2. Code Reusability :A single class can support multiple object creation scenarios.

3. Better Program Design “:It makes object initialization simple and organized.

4. Improved Readability :Programmers can easily understand how objects are created.

Volume of a Box

The formula for calculating the volume of a box is: V=l×b×hV = l \times b \times
hV=l×b×h

Where: l = Length b = Breadth h = Height

The calculated volume represents the total space occupied by the box.
Applications of Constructor Overloading

Constructor overloading is widely used in:

 Banking applications
 Student management systems
 Inventory management systems
 E-commerce applications
 Database applications
 Enterprise software development

In this experiment, two constructors are created to initialize box dimensions. One
constructor initializes default dimensions while the other initializes user-defined
dimensions. The volume is then calculated using the initialized values.

This experiment demonstrates how constructor overloading improves flexibility and


efficiency in object-oriented programming.

Task 1

Analyze how different constructors are invoked during object creation and identify the
values assigned to object attributes by each constructor.

Task 2

Modify the program by creating an additional constructor that accepts only one parameter
and initializes a cube. Explain how constructor overloading supports different object
initialization requirements.

PART B
Roll No : 0818CL241108 Name: Kunal Patil
Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


class Box {

int length;

int breadth;
int height;

Box() {

length = 1;

breadth = 1;

height = 1;

Box(int l, int b, int h) {

length = l;

breadth = b;

height = h;

int calculateVolume() {

return length * breadth * height;

public static void main(String[] args) {

[Link]("Name: Kunal Patil");

[Link]("Roll No.: 0818CL241108");

Box box1 = new Box();

Box box2 = new Box(2, 3, 4);


[Link]("Volume of Box 1 = " + [Link]());

[Link]("Volume of Box 2 = " + [Link]());

B.2 Input and Output

B.3 Observations and Learning

During the execution of the program, it was observed that constructors are automatically
called when objects are created. The default constructor initialized the dimensions of the
first box with predefined values, while the parameterized constructor initialized the
second box with user-specified values.

Students observed that:

 Constructors eliminate the need for separate initialization methods.


 Different constructors can initialize objects in different ways.
 Constructor overloading increases flexibility during object creation.
 Objects can be assigned unique properties at the time of creation.
 The compiler selects the appropriate constructor based on the argument list.

The experiment demonstrated how constructor overloading simplifies object initialization


and improves program design. Students gained practical understanding of object creation,
memory allocation, and initialization mechanisms in Java.

B.4 Conclusion

From this experiment, it can be concluded that constructor overloading is an important


feature of Java that enables objects to be initialized using different sets of parameters. It
improves flexibility, readability, and maintainability of programs by allowing multiple
initialization options within a single class.
Students successfully learned the difference between default and parameterized
constructors and understood how constructor overloading supports efficient object
creation. The concept is widely used in real-world software development where objects
require different initialization requirements.

The experiment strengthened understanding of object-oriented programming principles


and enhanced programming, analytical, and problem-solving skills.

B.5 Questions of Curiosity

1. What is a constructor in Java?

Answer:
A constructor is a special method used to initialize objects.
It has the same name as the class.
It is called automatically when an object is created.
It does not have a return type.
It initializes the object's data members.

2. How is a constructor different from a method?

Answer:
A constructor initializes an object.
A method performs a specific task.
A constructor has no return type.
A method may return a value.
A constructor is called automatically, while a method is called explicitly.

3. What is constructor overloading?

Answer:
Constructor overloading means having multiple constructors in the same class.
Each constructor has a different parameter list.
It allows different ways of creating objects.
The compiler selects the correct constructor automatically.
It improves flexibility in object creation.

4. Why are constructors automatically invoked?


Answer:
Constructors are called automatically when an object is created.
They initialize the object with default or given values.
This ensures the object is ready to use.
No separate method call is required.
It simplifies object creation.

5. Can a constructor return a value? Why?

Answer:
No, a constructor cannot return a value.
It does not have a return type.
Its purpose is to initialize the object.
Java automatically calls it during object creation.
Returning a value from a constructor is not allowed.

6. What are the advantages of constructor overloading in software development?

Answer:
It provides multiple ways to initialize objects.
It improves code flexibility.
It reduces code duplication.
It makes programs easier to understand.
It supports reusable and maintainable code.

7. How is constructor overloading different from method overloading?

Answer:
Constructor overloading uses multiple constructors with different parameters.
Method overloading uses multiple methods with the same name.
Constructors initialize objects.
Methods perform specific operations.
Both support compile-time polymorphism
Experiment No. 5
PART A

A.1 Aim

To write a program to show the details of students using the concept of inheritance.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Java program structure


 Classes and objects
 Methods
 Constructors
 Access modifiers
 Basics of Object-Oriented Programming
 Concept of code reusability

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of inheritance in Java.


2. Create parent and child classes using the extends keyword.
3. Access inherited data members and methods.
4. Demonstrate code reusability using inheritance.
5. Develop hierarchical class structures.
6. Apply inheritance in real-world software applications.

A.4 Theory

Inheritance is one of the most important features of Object-Oriented Programming


(OOP). It allows one class to acquire the properties and behaviors of another class.

The class whose properties are inherited is called the Parent Class, Base Class, or
Superclass.

The class that inherits those properties is called the Child Class, Derived Class, or
Subclass.

Inheritance promotes:

1. Code Reusability 2. Extensibility


2. Maintainability 4. Hierarchical Classification
Syntax of Inheritance
class Parent {
}

class Child extends Parent {


}

The extends keyword is used to establish the inheritance relationship between classes.

Why Inheritance is Needed

1. Code Reusability : Instead of writing the same code repeatedly, a child class can reuse
the members of the parent class.

2. Reduced Redundancy :Common features can be written once in the parent class and
shared among multiple child classes.

3. Easy Maintenance :Changes made in the parent class automatically become available
to child classes.

4. Better Organization”:Classes can be organized in a hierarchical structure.

Types of Inheritance in Java

1. Single Inheritance

One child class inherits from one parent class.

class A { }

class B extends A { }
2. Multilevel Inheritance : A class inherits from another derived class.
class A { }

class B extends A { }

class C extends B { }
3. Hierarchical Inheritance : Multiple child classes inherit from a single parent class.
class A { }

class B extends A { }

class C extends A { }
Java does not support multiple inheritance through classes to avoid ambiguity problems,
but it can be achieved using interfaces.

Real-Life Example of Inheritance

Consider:

 Person
o Student
o Teacher

Every student is a person and every teacher is a person. Therefore, common properties
such as name, age, and address can be placed in the Person class and inherited by Student
and Teacher classes.

Applications of Inheritance

Inheritance is widely used in:

 Student Management Systems


 Banking Applications
 Hospital Management Systems
 Employee Management Systems
 E-commerce Applications
 Enterprise Software

In this experiment, a parent class named Person contains common information, while a
child class named Student inherits these properties and displays student details.

The experiment demonstrates how inheritance promotes code reuse and simplifies
program development.

Task 1

Analyze the relationship between the parent class and child class and identify which
members are inherited by the child class.

Task 2

Modify the program by adding additional student information such as branch and
semester. Explain how inheritance reduces code duplication.
PART B
Roll No : 0818CL241108 Name : Kunal Patil
Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


class Person {

String name = "Rahul";

class Student extends Person {

int rollNo = 101;

String branch = "CSE";

void display() {

[Link]("Name: Kunal Patil");

[Link]("Roll No.: 0818CL241108");

[Link]("Student Name = " + name);

[Link]("Roll Number = " + rollNo);

[Link]("Branch = " + branch);

}
public static void main(String[] args) {

Student s = new Student();

[Link]();

B.2 Input and Output

B.3 Observations and Learning

During the execution of the program, it was observed that the child class successfully
inherited the data members of the parent class. The Student class accessed the variable
name directly without redefining it, demonstrating the concept of code reusability.

Students observed that:

 The extends keyword establishes an inheritance relationship.


 Child classes can access members of the parent class.
 Inheritance eliminates redundant code.
 Common properties can be maintained in a single parent class.
 Programs become easier to manage and extend.

The experiment clearly demonstrated how Java supports inheritance and how it simplifies
software development by creating hierarchical relationships among classes.

Students gained practical understanding of parent-child relationships and learned how


object-oriented systems are designed using inheritance.

B.4 Conclusion

From this experiment, it can be concluded that inheritance is a fundamental feature of


Object-Oriented Programming that promotes code reusability and hierarchical
organization of classes. It enables developers to create new classes from existing classes,
reducing duplication and improving maintainability.

Students successfully learned how to create parent and child classes using the extends
keyword and how inherited members can be accessed by derived classes. The concept is
widely used in real-world software systems to develop scalable, efficient, and
maintainable applications.

The experiment enhanced object-oriented design skills, programming logic, and


understanding of software architecture.

B.5 Questions of Curiosity

1. What is inheritance in Java?

Answer:
Inheritance is an OOP feature in Java.
It allows one class to inherit the properties of another class.
The child class reuses the parent class members.
It reduces code duplication.
It improves code reusability.

2. What is the purpose of the extends keyword?

Answer:
The extends keyword creates an inheritance relationship.
It connects the child class to the parent class.
The child class can access inherited members.
It promotes code reuse.
It simplifies program development.

3. What is the difference between a parent class and a child class?

Answer:
A parent class contains common properties and methods.
A child class inherits those members.
The child class can also have its own members.
The parent class is also called the superclass.
The child class is also called the subclass.

4. What are the advantages of inheritance?


Answer:
Inheritance improves code reusability.
It reduces code duplication.
It makes programs easier to maintain.
It supports hierarchical class design.
It improves software development efficiency.

5. Why does Java not support multiple inheritance through classes?

Answer:
Java avoids ambiguity problems.
Multiple inheritance may create confusion when methods have the same name.
This is called the Diamond Problem.
Java uses interfaces to achieve multiple inheritance.
This keeps programs simple and reliable.

6. How does inheritance improve code reusability?

Answer:
Common code is written only once in the parent class.
The child class inherits the common members.
There is no need to rewrite the same code.
It reduces redundancy.
It makes programs easier to update.

7. What are the different types of inheritance available in Java?

Answer:
Java supports single inheritance.
It also supports multilevel inheritance.
Hierarchical inheritance is also supported.
Multiple inheritance is supported only through interfaces.
These types improve code organization.

8. Where is inheritance used in real-world software applications?

Answer:
Inheritance is used in student management systems.
It is used in banking applications.
Hospital management software also uses [Link] and e-commerce
systems use it.
It is widely used in enterprise application
Experiment No. 6
PART A

A.1 Aim

To write a program to demonstrate the package concept.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Access modifiers
 Compilation and execution of Java programs
 Basic Object-Oriented Programming concepts
 Directory structure in Java

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of packages in Java.


2. Create and use user-defined packages.
3. Organize related classes into logical groups.
4. Import package classes into Java programs.
5. Improve code modularity and maintainability.
6. Develop large-scale Java applications using packages.

A.4 Theory

A Package in Java is a mechanism used to organize related classes, interfaces, and sub-
packages into a single namespace. Packages help in managing large projects by grouping
similar classes together.

In simple words, a package is similar to a folder in a computer system that contains


related files.

For example:

java
├── util
├── io
├── lang
├── net
Here:

 [Link] contains utility classes.


 [Link] contains input-output classes.
 [Link] contains core Java classes.
 [Link] contains networking classes.

Why Packages are Needed

1. Avoid Naming Conflicts :Two classes can have the same name if they belong to
different packages.

Example:

[Link]
[Link]

Both classes have the same name but belong to different packages.

2. Better Organization :Packages organize related classes into meaningful groups.

3. Access Protection:Packages provide package-level access control for classes and


members.

4. Code Reusability :Classes in packages can be imported and reused in different


applications.

5. Easy Maintenance :Large projects become easier to manage and maintain.

Types of Packages

1. Built-in Packages

These are predefined packages provided by Java.

Examples:

[Link]
[Link]
[Link]
[Link]
[Link]
2. User-Defined Packages

These are packages created by programmers.


Example:

package mypack;
Creating a Package

Step 1: Create Package


package mypack;
Step 2: Create Class Inside Package
package mypack;

public class Demo {

}
Step 3: Compile Package
javac -d . [Link]
Step 4: Import Package
import [Link];

Package Syntax
package package_name;

Example:

package mypack;
Importing a Package

A package can be imported using the import keyword.

Example:

import [Link];

or

import mypack.*;

The * symbol imports all classes available in the package.

Applications of Packages

Packages are widely used in:


 Enterprise Applications
 Banking Systems
 E-Commerce Platforms
 Android Development
 Web Applications
 Software Libraries

Packages play a vital role in large software projects where hundreds or thousands of
classes are involved.

In this experiment, a user-defined package named mypack is created, and a class is


placed inside the package. The class is then accessed and used in another program.

This experiment demonstrates how packages help organize Java applications efficiently.

Task 1

Analyze how packages help in avoiding class name conflicts in large software projects.

Task 2

Create another class inside the same package and explain how multiple related classes
can be organized within a package.
PART B
Roll No ; Kunal Patil Name; 0818CL241108
Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


package mypack;

public class Demo {

public void display() {

[Link]("Name: Kunal Patil");

[Link]("Roll No.: 0818CL241108");

[Link]("Package Concept Example");

import [Link];

public class PackageTest {

public static void main(String[] args) {

Demo obj = new Demo();

[Link]();

B.2 Input and Output

Sample Input
No user input required
B.3 Observations and Learning

During the execution of the program, it was observed that Java allows classes to be
grouped into packages for better organization and management. The package class was
successfully imported into another program using the import statement and its methods
were accessed without any difficulty.

Students observed that:

 Packages organize related classes into a logical structure.


 The package keyword is used to create packages.
 The import keyword allows access to package classes.
 Packages help avoid naming conflicts.
 Large projects become easier to manage using packages.
 Code reusability increases through package usage.

The experiment provided practical understanding of how Java applications are structured
and organized in professional software development environments.
Experiment No. 7
PART A

A.1 Aim

To write a program to demonstrate the implementation of an interface which


contains two method declarations, namely square() and cube().

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Object-Oriented Programming concepts


 Access modifiers
 Basic mathematical operations

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of interfaces in Java.


2. Declare and implement interfaces.
3. Override interface methods in implementing classes.
4. Achieve abstraction using interfaces.
5. Develop flexible and reusable Java programs.
6. Differentiate between inheritance and interface implementation.

A.4 Theory

An Interface in Java is a reference type that contains method declarations and constants.
It is used to achieve abstraction and multiple inheritance in Java.

Interfaces define what a class should do, but not how it should do it. The actual
implementation of interface methods is provided by the class that implements the
interface.

An interface acts as a contract between the interface and the implementing class.

Why Interfaces are Needed

Interfaces are used to:

 Achieve abstraction.
 Support multiple inheritance.
 Improve program flexibility.
 Promote loose coupling.
 Standardize behavior across different classes.

Declaration of Interface

Syntax:

interface InterfaceName {
methodDeclaration();
}

Example:

interface Shape {
void square(int x);
void cube(int x);
}

Here, the methods are only declared and not defined.

Implementing an Interface

A class implements an interface using the implements keyword.

Syntax:

class Demo implements Shape {


}

The implementing class must provide definitions for all interface methods.

Method Overriding in Interfaces

When a class implements an interface, it must override all declared methods.

Example:

public void square(int x) {


[Link](x * x);

}
Achieving Abstraction : Abstraction means hiding implementation details and showing
only essential features.

Example:

When a user presses a button in an application, they know what it does but not how the
internal code works.

Interfaces help achieve this abstraction.

Multiple Inheritance Using Interfaces :Java does not support multiple inheritance through
classes, but it supports multiple inheritance through interfaces.

Example:

interface A { }

interface B { }

class C implements A, B { }

This allows a class to inherit behavior specifications from multiple interfaces.

Advantages of Interfaces

1. Abstraction : Implementation details remain hidden.

2. Flexibility :Different classes can provide different implementations.

3. Reusability :Interfaces can be used across multiple projects.

4. Multiple Inheritance :A class can implement multiple interfaces.

5. Better Software Design :Interfaces promote modular and scalable systems.

Real-World Applications of Interfaces

Interfaces are extensively used in:

 Database Connectivity (JDBC)


 GUI Development
 Enterprise Applications
 Banking Systems
 Android Development
 Framework Design
Working of This Program

In this experiment:

 An interface named Shape is created.


 It contains two methods:
o square()
o cube()
 A class named Demo implements the interface.
 The class provides definitions for both methods.
 The methods calculate and display square and cube of a number.

This experiment demonstrates abstraction and interface implementation in Java.

Task 1

Analyze the role of interfaces in achieving abstraction and identify how the implementing
class provides functionality for interface methods.

Task 2

Modify the interface by adding another method named fourthPower() and implement it in
the class. Explain how interfaces support extensibility.
PART B
Roll No; 0818CL241108 Name: Kunal Patil
Program: [Link] AIML Second Year Division: AIML 2
Semester: IV Batch : B1
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


interface Shape {

void square(int x);

void cube(int x);

class Demo implements Shape {

public void square(int x) {

[Link]("Square = " + (x * x));

public void cube(int x) {

[Link]("Cube = " + (x * x * x));

public static void main(String[] args) {

[Link]("Name: Kunal Patil");

[Link]("Roll No.: 0818CL241108");

Demo obj = new Demo();

[Link](5);

[Link](5);

}
B.2 Input and Output

Sample Input
Number = 5

Sample Output

B.3 Observations and Learning

During the execution of the program, it was observed that the interface successfully
defined the behavior that must be implemented by the class. The implementing class
provided definitions for all declared methods and executed them correctly.

Students observed that:

 Interfaces contain method declarations.


 The implements keyword is used to implement interfaces.
 All interface methods must be overridden.
 Interfaces support abstraction.
 A class can implement multiple interfaces.
 Interface-based programming improves software flexibility.

The experiment demonstrated how interfaces separate method declarations from their
implementations. Students gained practical understanding of abstraction and learned how
interfaces contribute to modular and maintainable software design.

B.4 Conclusion

From this experiment, it can be concluded that interfaces are an important feature of Java
used to achieve abstraction and multiple inheritance. They provide a mechanism for
defining common behavior while allowing different classes to implement that behavior in
their own way.

Students successfully learned how to declare interfaces, implement them in classes, and
override interface methods. The experiment highlighted the role of interfaces in creating
scalable, reusable, and loosely coupled software systems.

The knowledge gained from this experiment is fundamental for advanced Java
technologies such as JDBC, Servlets, Spring Framework, Android Development, and
Enterprise Application Development.
B.5 Questions of Curiosity

1. What is an interface in Java?

Answer:
An interface is a reference type in Java.
It contains method declarations and constants.
It is used to achieve abstraction.
Classes implement interfaces using the implements keyword.
Interfaces improve software flexibility.

2. How is an interface different from a class?

Answer:
An interface contains only method declarations (except default/static methods).
A class contains both data members and method implementations.
Interfaces cannot be instantiated directly.
Classes can create objects.
Interfaces define behavior, while classes provide implementation.

3. Why are interfaces used in software development?

Answer:
Interfaces promote abstraction.
They improve code reusability.
They support multiple inheritance.
They reduce dependency between classes.
They make software easier to maintain.

4. What is the purpose of the implements keyword?

Answer:
The implements keyword is used to implement an interface.
It connects a class with an interface.
The class must define all interface methods.
It enables abstraction in Java.
It supports interface-based programming.

5. Can a class implement more than one interface?

Answer:
Yes, a class can implement multiple interfaces.
Java supports multiple inheritance through interfaces.
The class must implement all interface methods.
This increases flexibility in programming.
It helps build modular applications.
6. Why is interface-based programming preferred in large applications?

Answer:
It reduces coupling between classes.
It improves code flexibility.
It makes software easier to extend.
It supports reusable components.
It simplifies maintenance in large projects.

7. How do interfaces help achieve abstraction?

Answer:
Interfaces hide implementation details.
They define only method declarations.
The implementation is provided by the class.
Users interact with the interface, not the implementation.
This improves program design.

8. Where are interfaces commonly used in real-world software systems?

Answer:
Interfaces are used in JDBC.
They are used in Android development.
Enterprise applications use interfaces extensively.
Spring Framework also uses interfaces.
They are common in banking and web applications.
Experiment No. 8
PART A

A.1 Aim

To write a program to demonstrate exception handling in case of division by zero


error.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Basic understanding of program execution flow


 Runtime errors and logical errors

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of exception handling in Java.


2. Differentiate between compile-time errors and runtime errors.
3. Use try and catch blocks to handle exceptions.
4. Prevent abnormal program termination.
5. Develop robust and user-friendly applications.
6. Apply exception handling techniques in real-world software development.

A.4 Theory

Exception Handling is a mechanism used to handle runtime errors so that the normal flow
of a program can be maintained.

An Exception is an unwanted event that occurs during program execution and disrupts
the normal execution flow of the program.

Examples of exceptions include:

 Division by zero
 Array index out of bounds
 Invalid user input
 File not found
 Null pointer access

Without exception handling, a program may terminate unexpectedly when an error


occurs.
Need for Exception Handling

Exception handling is important because:

1. Prevents Program Crashes : The program can continue execution even after an error
occurs.

2. Improves Reliability : Applications become more stable and dependable.

3. Simplifies Error Management :Errors can be handled in a centralized manner.

4. Improves User Experience : Meaningful error messages can be displayed instead of


abrupt termination.

Types of Errors in Java

1. Compile-Time Errors : Errors detected during compilation.

Example:

int x = "Hello";

The compiler detects the error before execution.

2. Runtime Errors : Errors that occur during execution.

Example:

int result = 10 / 0;

This causes an ArithmeticException.

3. Logical Errors : The program runs successfully but produces incorrect output.

Example:

int area = length + breadth;

instead of

int area = length * breadth;


Exception Handling Keywords

Java provides five important keywords:


try
Used to enclose code that may generate an exception.
try {

}
catch
Used to handle the exception.
catch(Exception e) {

}
finally
Executes regardless of whether an exception occurs.
finally {

throw
Used to explicitly generate an exception.

throws
Used to declare exceptions.

Syntax of Exception Handling


try {

// Risky code

}
catch(ExceptionType e) {

// Handling code

}
ArithmeticException

An ArithmeticException occurs when an illegal arithmetic operation is performed.

Example:

int result = 10 / 0;

Output:

Exception in thread "main"


[Link]
To avoid abnormal termination, we use exception handling.

Working of the Program

The program attempts to divide a number by zero.

Execution flow:

1. Program enters the try block.


2. Division by zero occurs.
3. Java generates an ArithmeticException.
4. Control transfers to the catch block.
5. Error message is displayed.
6. Program terminates normally.

This mechanism ensures safe execution of programs.

Real-World Applications

Exception handling is widely used in:

 Banking Systems
 ATM Applications
 Online Payment Systems
 Database Applications
 Hospital Management Systems
 Enterprise Software
 Web Applications

Without exception handling, large software systems would frequently crash during
execution.

Task 1

Analyze how program execution changes when the division operation is placed inside
and outside the try block.

Task 2

Modify the program to handle multiple exceptions and identify how Java selects the
appropriate catch block during execution.
PART B

Roll No. Name


Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


class DivisionExceptionDemo {

public static void main(String[] args) {

try {

int numerator = 100;

int denominator = 0;

int result = numerator / denominator;

[Link]("Result = " + result);

catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}

[Link]("Program executed successfully.");


}
}

B.2 Input and Output

Sample Input
Numerator = 100
Denominator = 0
Sample Output
Error: Division by zero is not allowed.
Program executed successfully.
B.3 Observations and Learning

During the execution of the program, it was observed that division by zero generated an
ArithmeticException. Instead of terminating abruptly, the exception was handled by the
catch block, allowing the program to continue execution normally.

Students observed that:

 Runtime errors generate exceptions.


 The try block contains code that may cause exceptions.
 The catch block handles exceptions gracefully.
 Exception handling prevents abrupt program termination.
 Meaningful error messages improve program usability.
 Programs become more reliable and robust.

The experiment provided practical understanding of Java's exception handling


mechanism and demonstrated how software applications can recover from runtime errors
efficiently.

B.4 Conclusion

From this experiment, it can be concluded that exception handling is an essential feature
of Java used to manage runtime errors effectively. It enables programs to handle
unexpected situations without crashing and ensures smooth execution.

Students successfully learned how to use try and catch blocks to handle
ArithmeticException caused by division by zero. The experiment highlighted the
importance of error handling in developing secure, reliable, and user-friendly software
applications.

The knowledge gained from this experiment is crucial for building enterprise-level
systems where fault tolerance and reliability are critical requirements.

B.5 Questions of Curiosity

1. What is an exception in Java?


2. What is the difference between an error and an exception?
3. Why is exception handling important?
4. What is the purpose of the try block?
5. What is the role of the catch block?
6. What happens if an exception is not handled?
7. What is an ArithmeticException?
8. How does exception handling improve software reliability?
9. What is the difference between throw and throws?
10. Where is exception handling commonly used in real-world applications?
Experiment No. 9
PART A

A.1 Aim

To write a program to demonstrate multithreading in Java.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Java program structure


 Classes and objects
 Methods and constructors
 Inheritance
 Loops and control statements
 Basic Object-Oriented Programming concepts
 Program execution flow

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of multithreading in Java.


2. Create and execute threads using the Thread class.
3. Implement concurrent execution of tasks.
4. Differentiate between single-threaded and multithreaded programs.
5. Improve application performance using multithreading.
6. Apply multithreading concepts in real-world software applications.

A.4 Theory

Multithreading is a feature of Java that allows multiple threads to execute concurrently


within a program. A thread is the smallest unit of execution within a process.

A process may contain one or more threads. Each thread performs a specific task
independently while sharing the same memory space.

For example:

 A web browser can download files while displaying web pages.


 A music player can play music while updating the user interface.
 An IDE can compile code while allowing the user to edit files.

These activities are possible because of multithreading.


What is a Thread?

A thread is a lightweight subprocess that executes independently within a program.

Every Java program contains at least one thread known as the Main Thread.

Example:

public static void main(String[] args)

The main() method runs within the main thread.

Why Multithreading is Needed

1. Better CPU Utilization

Multiple tasks can execute simultaneously.

2. Faster Execution

Programs become more responsive and efficient.

3. Improved User Experience

Applications remain interactive while background tasks execute.

4. Resource Sharing

Threads share memory resources efficiently.

5. Concurrent Task Execution

Multiple operations can run at the same time.

Life Cycle of a Thread

A thread passes through several states:

1. New State
2. Runnable State
3. Running State
4. Blocked/Waiting State
5. Terminated State

Flow:
New → Runnable → Running → Waiting/Blocked → Terminated

Creating a Thread in Java

There are two common ways:

Method 1: Extending Thread Class


class MyThread extends Thread {

public void run() {

}
}

The run() method contains the task performed by the thread.

The thread starts execution using:

[Link]();

Method 2: Implementing Runnable Interface


class MyThread implements Runnable {

public void run() {

}
}

This approach is preferred because Java supports single inheritance.

Difference Between start() and run()


start() run()

Creates a new thread Executes as a normal method

Concurrent execution No concurrent execution

Invokes JVM thread scheduler Does not create a new thread

Thread Scheduler

The JVM contains a thread scheduler that determines which thread executes at a
particular time.
Because scheduling is controlled by the JVM and operating system, thread execution
order may vary.

Applications of Multithreading

Multithreading is widely used in:

 Operating Systems
 Web Browsers
 Gaming Applications
 Banking Systems
 Online Reservation Systems
 Mobile Applications
 Multimedia Software
 Network Applications

Working of the Program

In this experiment:

1. A class named MyThread extends the Thread class.


2. The run() method contains the code executed by the thread.
3. An object of the thread class is created.
4. The start() method is invoked.
5. The JVM creates a new thread and executes the run() method.

This demonstrates concurrent task execution using Java multithreading.

Task 1

Analyze the difference between calling start() and run() methods and explain how thread
execution changes in each case.

Task 2

Modify the program by creating a second thread and identify how multiple threads
execute concurrently.
PART B
Roll No. Name
Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Thread Execution : " + i);
}
}

public static void main(String[] args) {


MyThread t1 = new MyThread();
[Link]();
[Link]("Main Thread Executed");
}
}

B.2 Input and Output

Sample Input
No user input required.
Sample Output
Main Thread Executed

Thread Execution : 1
Thread Execution : 2
Thread Execution : 3
Thread Execution : 4
Thread Execution : 5

Note: Output order may vary because thread scheduling is controlled by the JVM.
B.3 Observations and Learning

During the execution of the program, it was observed that a separate thread was created
and executed independently of the main thread. The thread executed the statements inside
the run() method while the main thread continued its execution.

Students observed that:

 Every Java program contains a main thread.


 New threads can be created using the Thread class.
 The start() method initiates thread execution.
 The run() method contains the thread's task.
 Multiple threads can execute concurrently.
 Thread execution order may vary due to JVM scheduling.

The experiment provided practical exposure to concurrent programming and


demonstrated how multithreading improves program responsiveness and efficiency.

Students gained understanding of thread creation, execution, scheduling, and lifecycle


management.

B.4 Conclusion

From this experiment, it can be concluded that multithreading is a powerful feature of


Java that enables concurrent execution of multiple tasks within a single program. It
improves CPU utilization, application responsiveness, and overall performance.

Students successfully learned how to create and execute threads using the Thread class
and understood the role of the start() and run() methods. The experiment highlighted the
importance of multithreading in modern software development, where multiple tasks
often need to execute simultaneously.

The knowledge gained from this experiment forms the foundation for advanced concepts
such as thread synchronization, concurrency control, parallel processing, and distributed
computing.

B.5 Questions of Curiosity

1. Why is multithreading used?


2. What is the purpose of the run() method?
3. What is the role of the start() method?
4. What is the difference between start() and run()?
5. Can multiple threads share the same memory?
6. What is thread scheduling?
7. What are the advantages of multithreading?
8. Where is multithreading used in real-world applications?
Experiment No. 10
PART A

A.1 Aim

To write a program to demonstrate JDBC concept using create a GUI based


application for student information.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Exception handling
 GUI programming using AWT/Swing
 Relational Database Management Systems (RDBMS)
 SQL commands (INSERT, UPDATE, DELETE, SELECT)
 MySQL database basics
 Java packages and libraries

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of JDBC in Java.


2. Establish connectivity between Java applications and databases.
3. Perform database operations using SQL queries.
4. Develop GUI-based applications integrated with databases.
5. Handle database exceptions effectively.
6. Design simple database-driven software applications.

A.4 Theory

Introduction to JDBC

JDBC (Java Database Connectivity) is an API provided by Java that enables Java
applications to interact with relational databases such as MySQL, Oracle, SQL Server,
PostgreSQL, and others.

JDBC acts as a bridge between a Java application and a database.

Using JDBC, a programmer can:

 Connect to a database.
 Execute SQL statements.
 Retrieve data from tables.
 Insert, update, and delete records.
 Manage transactions.

Need for JDBC

In modern applications, data must be stored permanently. Variables store data


temporarily in memory, but databases provide permanent storage.

Examples:

 Student Information Systems


 Banking Applications
 Hospital Management Systems
 Railway Reservation Systems
 E-commerce Applications

All these applications use databases.

JDBC Architecture
Java Application
|
v
JDBC API
|
v
JDBC Driver
|
v
Database

The JDBC Driver translates Java commands into database-specific commands.

JDBC Components

1. Driver Manager : Used to establish a connection with the database.


[Link]()
2. Connection :Represents the connection between Java application and database.
Connection con;
3. Statement : Used to execute SQL queries.
Statement st;
4. ResultSet : Stores data returned from SQL queries.
ResultSet rs;
Steps for JDBC Connectivity

Step 1: Import JDBC Package


import [Link].*;
Step 2: Load Driver
[Link]("[Link]");
Step 3: Establish Connection
Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");
Step 4: Create Statement
Statement st =
[Link]();
Step 5: Execute Query
[Link](query);

or

ResultSet rs =
[Link](query);
Step 6: Close Connection
[Link]();
GUI-Based Student Information System

A GUI-based application provides a graphical interface through which users can:

 Enter student details.


 Store records in the database.
 Search student information.
 Update records.
 Delete records.

This makes applications more user-friendly.

Advantages of JDBC

1. Platform Independent
2. Database Independent
3. Secure Data Storage
4. Supports SQL Queries
5. Easy Database Integration
6. Widely Used in Enterprise Applications

Applications of JDBC

JDBC is widely used in:

 Banking Systems
 Student Management Systems
 Employee Management Systems
 Hospital Management Systems
 Inventory Systems
 E-Commerce Platforms

Working of This Program

In this experiment:

1. A GUI form is created using Swing.


2. Student information is entered through text fields.
3. JDBC establishes connection with MySQL database.
4. SQL INSERT query stores student information.
5. A success message is displayed.

The experiment demonstrates integration of Java GUI applications with databases using
JDBC.

Task 1

Analyze the role of JDBC Driver, Connection, Statement, and ResultSet objects in
establishing communication between Java applications and databases.

Task 2

Modify the application to include functionality for updating and deleting student records
and explain the SQL queries required.
PART B
Roll No. Name
Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student

Student Information System Using JDBC and Swing


import [Link].*;
import [Link].*;
import [Link].*;

public class StudentInfo extends JFrame {

JLabel l1, l2;


JTextField t1, t2;
JButton save;

StudentInfo() {

l1 = new JLabel("Roll Number");


l2 = new JLabel("Student Name");

t1 = new JTextField();
t2 = new JTextField();

save = new JButton("Save");

[Link](50,50,100,30);
[Link](180,50,150,30);

[Link](50,100,100,30);
[Link](180,100,150,30);

[Link](120,170,100,30);

add(l1);
add(t1);
add(l2);
add(t2);
add(save);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {

try {

[Link](
"[Link]");

Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");

String query =
"insert into student values(?,?)";

PreparedStatement ps =
[Link](query);

[Link](1,
[Link]([Link]()));

[Link](2,
[Link]());

[Link]();

[Link](
null,
"Record Saved Successfully");

[Link]();

} catch(Exception ex) {

[Link](ex);

}
}
});

setSize(450,350);
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {

new StudentInfo();
}
}
B.2 Input and Output

Sample Input
Roll Number : 101
Student Name : Rahul Sharma
Sample Output
Record Saved Successfully

Database Table:

Roll No Student Name

101 Rahul Sharma

B.3 Observations and Learning

During the execution of the program, it was observed that JDBC successfully established
a connection between the Java application and the MySQL database. Student information
entered through the GUI form was stored in the database table using SQL queries.

Students observed that:

 JDBC enables communication between Java applications and databases.


 GUI components improve user interaction.
 SQL queries can be executed through Java programs.
 Database records can be inserted programmatically.
 JDBC drivers play a crucial role in connectivity.
 Exceptions must be handled during database operations.

The experiment provided practical experience in integrating Java applications with


databases and helped students understand how real-world information systems manage
and store data.

B.4 Conclusion

From this experiment, it can be concluded that JDBC is an essential technology for
developing database-driven Java applications. It provides a standardized mechanism for
connecting Java programs with relational databases and performing data manipulation
operations.

Students successfully learned how to establish database connections, execute SQL


queries, and integrate graphical user interfaces with databases. The experiment
demonstrated the importance of persistent data storage and highlighted the role of JDBC
in enterprise software development.

The knowledge gained from this experiment forms the foundation for advanced
technologies such as Servlets, JSP, Hibernate, Spring Framework, and Enterprise Java
Applications.

B.5 Questions of Curiosity

1. What is JDBC?
2. Why is JDBC required in Java applications?
3. What is the role of a JDBC Driver?
4. What is the difference between Statement and PreparedStatement?
5. Why are databases important in software systems?
6. What is a ResultSet?
7. How does JDBC improve data management?
8. What are the advantages of using PreparedStatement over Statement?
9. Which databases can be connected using JDBC?
10. How is JDBC used in enterprise applications?
Experiment No. 12
PART A

A.1 Aim

To write a program to add user controls to applets.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Java Applets
 AWT components
 Event handling basics
 GUI programming concepts

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of user controls in applets.


2. Create graphical user interfaces using AWT components.
3. Add controls such as buttons, labels, text fields, and checkboxes to applets.
4. Handle user interactions through GUI components.
5. Design interactive applet-based applications.
6. Apply event-driven programming concepts.

A.4 Theory

A User Control is a graphical component that allows users to interact with an


application. In Java Applets, user controls are added using the Abstract Window Toolkit
(AWT) package.

Common user controls include:

 Button
 Label
 TextField
 Checkbox
 Choice
 List
 TextArea

These controls help create interactive applications where users can enter data, make
selections, and trigger actions.
Common AWT Controls

Button : Used to perform an action when clicked.

Button b = new Button("Submit");

Label : Used to display text.

Label l = new Label("Enter Name");

TextField :Used to accept single-line input.

TextField t = new TextField(20);

Checkbox : Used for multiple selections.


Checkbox cb = new Checkbox("Java");
Advantages of User Controls

 Improved user interaction


 Better interface design
 Easy data entry
 Enhanced user experience
 Interactive applications

Applications

 Online Forms
 Educational Software
 Banking Systems
 Reservation Systems
 GUI Applications

In this experiment, a button and text field are added to an applet to demonstrate user
controls.

Task 1

Analyze the role of different AWT controls and identify where each control is commonly
used.

Task 2

Modify the applet by adding additional controls such as Checkbox and Choice
components and explain their functionality.
PART B
Roll No. Name
Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


import [Link];
import [Link].*;

public class UserControlApplet extends Applet {

Label l1;
TextField t1;
Button b1;

public void init() {

l1 = new Label("Enter Name:");

t1 = new TextField(20);

b1 = new Button("Submit");

add(l1);
add(t1);
add(b1);
}
}
B.2 Input and Output

Sample Input
Enter Name: Rahul
Sample Output
Applet displays:
Label : Enter Name
Text Field
Submit Button
B.3 Observations and Learning

During the execution of the applet, it was observed that graphical controls could be easily
added using AWT components. The controls were displayed properly and allowed user
interaction.

Students observed that:

 Applets support GUI controls.


 AWT components provide user interaction.
 Controls can be arranged within applets.
 User input can be collected through text fields.
 Buttons can trigger application actions.

The experiment helped students understand GUI development and event-driven


programming concepts.

B.4 Conclusion

From this experiment, it can be concluded that user controls are essential for developing
interactive applications. Java Applets provide support for various GUI components
through AWT.

Students successfully learned how to add controls to applets and create simple user
interfaces. The concept forms the foundation for advanced GUI development using
Swing and JavaFX.

B.5 Questions of Curiosity

1. What are user controls in Java?


2. What is AWT?
3. What is the purpose of a TextField?
4. How is a Button different from a Label?
5. What are the advantages of GUI-based applications?
6. How do user controls improve usability?
7. What is event handling?
8. Where are AWT controls commonly used?
Experiment No. 13
PART A

A.1 Aim

To write a program to create an application using the concept of Swing.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Event handling
 GUI programming basics
 AWT concepts
 Methods and constructors

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of Swing in Java.


2. Create GUI-based applications using Swing components.
3. Design windows, buttons, labels, and text fields.
4. Develop event-driven applications.
5. Build platform-independent graphical applications.
6. Apply Swing components in software development.

A.4 Theory

Swing is a part of the Java Foundation Classes (JFC) and is used for developing
platform-independent graphical user interfaces.

Swing provides a rich set of GUI components that are more powerful and flexible than
AWT components.

Features of Swing

 Platform Independent
 Lightweight Components
 Rich GUI Controls
 MVC Architecture
 Customizable Components
Common Swing Components

JFrame : Top-level window container.

JFrame frame = new JFrame();

JButton : Creates a button.

JButton button = new JButton("Submit");

JLabel : Displays text.

JLabel label = new JLabel("Name");

JTextField : Accepts user input.

JTextField text = new JTextField();

Advantages of Swing

 Attractive GUI
 Cross-platform support
 Rich component library
 Easy event handling
 Professional application design

Applications of Swing

 Student Management Systems


 Banking Applications
 Inventory Systems
 Desktop Software
 Educational Applications

In this experiment, a simple Swing application is created using JFrame and JButton.

Task 1

Analyze the differences between AWT and Swing components and identify advantages
of Swing.

Task 2

Modify the application by adding labels and text fields to create a simple student
information form.
PART B
Roll No. Name
Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student


import [Link].*;

public class SwingDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Swing Application");


JButton button = new JButton("Click Me");
[Link](120,100,120,40);
[Link](button);
[Link](400,300);
[Link](null);
[Link](true);
[Link]( JFrame.EXIT_ON_CLOSE);
}
}
B.2 Input and Output

Sample Input
No user input required.
Sample Output
A window titled "Swing Application"
containing a button "Click Me"
is displayed on the screen.
B.3 Observations and Learning

During the execution of the program, it was observed that Swing components provided a
graphical interface for user interaction. The JFrame acted as the main window and the
JButton was displayed successfully.

Students observed that:

 Swing supports advanced GUI development.


 JFrame acts as a container for components.
 Components can be positioned within windows.
 Swing applications are platform independent.
 GUI applications improve user experience.

The experiment provided practical exposure to desktop application development using


Java Swing.

B.4 Conclusion

From this experiment, it can be concluded that Swing is a powerful framework for
developing graphical user interfaces in Java. It provides a rich set of components and
supports event-driven programming.

Students successfully learned how to create GUI windows and add Swing controls. The
concept serves as a foundation for developing professional desktop applications.

B.5 Questions of Curiosity

1. What is Swing?
2. How is Swing different from AWT?
3. What is the role of JFrame?
4. Why are Swing components called lightweight components?
5. What are the advantages of Swing?
6. How does Swing support platform independence?
7. What is event-driven programming?
8. Where are Swing applications commonly used?
Experiment No. 14
PART A

A.1 Aim

To write a program to demonstrate student registration functionality using Servlets


with Session Management.

A.2 Prerequisite

Before performing this experiment, students should have knowledge of:

 Java programming fundamentals


 Classes and objects
 Exception handling
 HTML forms
 Web application architecture
 HTTP protocol basics
 Client-Server communication
 Servlet technology
 Web servers such as Apache Tomcat

A.3 Outcome

After successful completion of this experiment, students will be able to:

1. Understand the concept of Java Servlets.


2. Develop web applications using Servlets.
3. Process user requests through HTML forms.
4. Implement session management in web applications.
5. Store and retrieve user information using HttpSession.
6. Develop dynamic and interactive web-based applications.
7. Understand state management in web environments.

A.4 Theory

Introduction to Servlets

A Servlet is a Java program that runs on a web server and handles client requests.
Servlets are used to create dynamic web applications.

A Servlet receives requests from clients (typically web browsers), processes the requests,
and generates responses.

Servlets are platform-independent because they are written in Java.


Need for Servlets

Traditional HTML pages are static and cannot process user requests dynamically.

Servlets provide:

 Dynamic content generation


 User interaction
 Database connectivity
 Session tracking
 Business logic implementation

Servlet Architecture
Client Browser
|
Request
|
Web Server (Tomcat)
|
Servlet
|
Response
|
Client Browser
Servlet Life Cycle

The Servlet life cycle consists of three important methods:

1. init()

Called once when the servlet is loaded.

public void init()


{
}
2. service()

Handles client requests.

public void service(


HttpServletRequest req,
HttpServletResponse res)
{
}
3. destroy()

Called before servlet removal.

public void destroy()


{
}
What is Session Management?

HTTP is a stateless protocol.

This means:

 The server does not remember previous requests.


 Each request is treated independently.

To maintain user information across multiple requests, session management is used.

Need for Session Management

Session management helps in:

 User authentication
 Shopping carts
 Online registration systems
 Banking applications
 E-learning portals

Without session management, user information would be lost after every request.

HttpSession : Java provides the HttpSession interface to manage sessions.

Creating a session: HttpSession session = [Link]();

Storing values: [Link]( "name","Rahul");

Retrieving values: String name = (String)[Link]( "name");

Advantages of Session Management

1. Maintains user state.


2. Improves user experience.
3. Supports authentication.
4. Enables secure transactions.
5. Allows data sharing across multiple pages.
Student Registration System

A student registration system generally performs:

 Accepting student details


 Validating user input
 Storing information
 Maintaining user session
 Displaying confirmation details

Working of This Program

In this experiment:

1. Student enters registration details.


2. Servlet receives the request.
3. Session object is created.
4. Student information is stored in the session.
5. Servlet displays registration confirmation.
6. Session maintains data throughout the interaction.

This experiment demonstrates how web applications preserve user information across
multiple requests.

Real-World Applications

Servlets and Session Management are widely used in:

 Student Portals
 Online Examination Systems
 Banking Applications
 E-Commerce Websites
 Hospital Management Systems
 Railway Reservation Systems
 ERP Solutions

Task 1

Analyze how session management overcomes the stateless nature of HTTP and identify
scenarios where maintaining user state is essential.

Task 2

Modify the registration system to store additional student details such as branch,
semester, and email address, and explain how session attributes can be used to manage
this information.
PART B
Roll No. Name
Program: [Link] AIML Second Year Division: AIML 1
Semester: IV Batch : B1 /B2
Date of Experiment: Date of Submission:
Grade :

B.1 Software Code Written by Student

[Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class StudentRegistrationServlet extends HttpServlet {

public void doPost( HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

String name = [Link]("name");

String roll = [Link]("roll");

HttpSession session = [Link]();

[Link]( "studentName", name);

[Link]( "studentRoll", roll);

[Link]("<html>");
[Link]("<body>");
[Link]("<h2>");
[Link]( "Student Registration Successful");
[Link]("</h2>");
[Link]( "<p>Name : " + name + "</p>");
[Link]( "<p>Roll No : "+ roll + "</p>");
[Link]("</body>");
[Link]("</html>");
}
}
[Link]
<html>
<body>
<form action="StudentRegistrationServlet" method="post">

Name : <input type="text" name="name">

<br><br>

Roll Number : <input type="text" name="roll">

<br><br>

<input type="submit" value="Register">

</form>
</body>
</html>
B.2 Input and Output

Sample Input
Student Name : Rahul Sharma
Roll Number : 101
Sample Output
Student Registration Successful

Name : Rahul Sharma


Roll No : 101

B.3 Observations and Learning

During the execution of the program, it was observed that the servlet successfully
processed the data submitted through the HTML form. The student details were received
through the HTTP request and stored within the session object.

Students observed that:

 Servlets process client requests dynamically.


 HTML forms can send data to servlets.
 HttpSession maintains information across requests.
 User data can be stored and retrieved using session attributes.
 Session management helps preserve user state.
 Web applications become interactive and user-friendly.
The experiment provided practical exposure to web-based application development and
demonstrated how server-side processing is performed using Java Servlets.

Students gained understanding of request processing, response generation, and session


tracking mechanisms.

B.4 Conclusion

From this experiment, it can be concluded that Java Servlets provide an effective
mechanism for developing dynamic web applications. Session management plays a
crucial role in maintaining user information across multiple interactions in a web
environment.

Students successfully learned how to process form data using servlets and how to use
HttpSession for preserving user information. The experiment highlighted the importance
of state management in web applications and demonstrated its practical implementation.

The knowledge gained from this experiment forms the foundation for advanced web
technologies such as JSP, JSTL, Spring MVC, Hibernate, and Enterprise Web
Application Development.

B.5 Questions of Curiosity

1. What is a Servlet?
2. Why are Servlets used in web applications?
3. What is the servlet life cycle?
4. Why is HTTP called a stateless protocol?
5. What is session management?
6. What is HttpSession?
7. How does a servlet process client requests?
8. What is the difference between GET and POST methods?
9. How are session attributes stored and retrieved?
10. Where is session management used in real-world applications?

You might also like