0% found this document useful (0 votes)
2 views72 pages

Java Lab Manual Org

The document is a Java lab manual detailing various experiments in Object-Oriented Programming using Java. It includes experiment titles, aims, prerequisites, outcomes, theories, tasks, and observations for each experiment, focusing on concepts like input/output operations, method overloading, and constructors. The manual aims to enhance students' understanding of Java programming fundamentals and practical applications.

Uploaded by

yashay158
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)
2 views72 pages

Java Lab Manual Org

The document is a Java lab manual detailing various experiments in Object-Oriented Programming using Java. It includes experiment titles, aims, prerequisites, outcomes, theories, tasks, and observations for each experiment, focusing on concepts like input/output operations, method overloading, and constructors. The manual aims to enhance students' understanding of Java programming fundamentals and practical applications.

Uploaded by

yashay158
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 Date Of Date Of Remarks


No. Experiment Submission
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.
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. 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:


B.2 Input and Output:

Sample Input
Enter first number: 15
Enter second number: 25
Sample Output
Sum of two numbers = 40

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?
• What is the difference between int, float, and double data types?

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

• Can the program be modified to add more than two numbers? How?

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


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

B.2 Input and Output


Sample Input
Number 1 = 25
Number 2 = 15
Sample Output
Addition = 40

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?

2. Why is a return statement important in a method?


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

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

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

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


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

B.2 Input and Output

Sample Input
Number 1 = 10
Number 2 = 20
Number 1 = 10
Number 2 = 20
Number 3 = 30
Sample Output
Average of 2 numbers = 15.0
Average of 3 numbers = 20.0

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?


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

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

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

5. What are the advantages of method overloading in software development


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

B.2Input and Output

Sample Input
Box 1 Dimensions:
Length = 1
Breadth = 1
Height = 1
Box 2 Dimensions:
Length = 2
Breadth = 3
Height = 4
Sample Output
Volume of Box 1 = 1
Volume of Box 2 = 24

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?


2. How is a constructor different from a method?

3. What is constructor overloading?

4. Why are constructors automatically invoked?

5. Can a constructor return a value? Why?

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

7. How is constructor overloading different from method overloading?


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

B.2 Input and Output

Sample Input
Student Name = Rahul
Roll Number = 101
Branch = CSE
Sample Output
Name = Rahul
Roll Number = 101
Branch = CSE

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?


2. What is the purpose of the extends keyword?

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

4. What are the advantages of inheritance?

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

6. How does inheritance improve code reusability?

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

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


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


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

B.2 Input and Output

Sample Input
No user input required
Sample Output
Package Concept Example
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
{ methodDeclaratio
n(); }

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

B.2 Input and Output

Sample Input
Number = 5
Sample Output
Square = 25
Cube = 125

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?


2. How is an interface different from a class?

3. Why are interfaces used in software development?

4. What is the purpose of the implements keyword?

5. Can a class implement more than one interface?

6. Why is interface-based programming preferred in large applications?

7. How do interfaces help achieve abstraction?


8. Where are interfaces commonly used in real-world software systems?
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 {
}
cat
ch
Used to handle the exception.
catch(Exception e) {

}
final
ly
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

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

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?

You might also like