0% found this document useful (0 votes)
6 views45 pages

Java Lab Manual Updated

The document outlines the Java Programming Lab course for the Computer Science and Engineering (AI&ML) program at Bharat Institute of Engineering and Technology. It includes the department's vision and mission, program educational objectives, outcomes, specific outcomes, and a detailed syllabus with experiments aimed at teaching Java programming concepts. The document also highlights the features of Java, its execution process, and applications, along with a specific experiment to familiarize students with IDE functionalities and basic Java programming.

Uploaded by

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

Java Lab Manual Updated

The document outlines the Java Programming Lab course for the Computer Science and Engineering (AI&ML) program at Bharat Institute of Engineering and Technology. It includes the department's vision and mission, program educational objectives, outcomes, specific outcomes, and a detailed syllabus with experiments aimed at teaching Java programming concepts. The document also highlights the features of Java, its execution process, and applications, along with a specific experiment to familiarize students with IDE functionalities and basic Java programming.

Uploaded by

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

DEPARTMENT OF CSE (AI&ML)

JAVA PROGRAMMING LAB


(CS407PC)

II YEAR [Link] II SEMESTER (R22)


AY: 2025-26
DEPARTMENT OF CSE

(ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING)


BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
Ibrahimpatnam - 501 510, Hyderabad.
DEPARTMENT OF CSE (AI&ML)

COLLEGE VISION AND MISSION

VISION
To achieve the autonomous & University status and spread universal
education by inculcating discipline, character and knowledge into the young
minds and mould them into enlightened citizens.

MISSION

Our mission is to impact high quality education in a conductive ambience


with the support of all the modern technologies and make the students acquire
the ability and passion to work wisely, creatively and effectively for the
betterment of our society.

DEPARTMENT OF CSE
(ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING)
BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
Ibrahimpatnam - 501 510, Hyderabad
DEPARTMENT OF CSE (AI&ML)

DEPARTMENT VISION AND MISSION

VISION
To establish a community of lifelong learners and industry leaders while
building an innovative, ethical, and internationally renowned center of
excellence in artificial intelligence and machine learning.

MISSION

Our goal is to give students a life-changing educational experience by


giving them the ethical principles, information, and abilities they need to
succeed in the quickly developing disciplines of machine learning and
artificial intelligence. In addition to supporting research and development
that tackles pressing issues and advances society, we are dedicated to
cultivating a culture of creativity, cooperation, and diversity.

DEPARTMENT OF CSE

(ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING)


BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY

Ibrahimpatnam - 501 510, Hyderabad


DEPARTMENT OF CSE (AI&ML)
A graduate of the Computer Science and Engineering(AI&ML) Program should :

Program Educational Objective 1: (PEO1)


The graduates of Computer Science and Engineering will have successful career in technology or
managerial functions.

Program Educational Objective 2: (PEO2)


The graduates of the program will have solid technical and professional foundation to continue
higher studies.

Program Educational Objective 3: (PEO3)


The graduates of the program will have skills to develop products, offer services and create new
knowledge.

Program Educational Objective 4: (PEO4)


The graduates of the program will have fundamental awareness of Industry processes, tools and
technologies.
DEPARTMENT OF CSE (AI&ML)
Program Outcomes(POs):
Engineering knowledge: To Apply the knowledge of mathematics, science and engineering
PO1 fundamentals/principles, in Computer Science Engineering to the solution of complex engineering
problems encountered in modern Engineering practice.

Problem analysis: Ability to Identify, formulate, review research literature, and analyze complex
PO2 engineering problems related to Electrical and Electronics Engineering and reaching substantiated
conclusions using first principles of mathematics, natural sciences, and engineering sciences.

Design/development of solutions: Design solutions for complex engineering problems related to


PO3 Electrical and Electronics Engineering and design system components or processes that meet the
desired needs within realistic consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research--based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
Engineering tool usage: Create, select, and apply appropriate techniques, skills, resources, and
PO5 modern Electrical and Electronics Engineering tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
Electrical and Electronics Engineering professional engineering practice.

PO7 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

Individual and team work: Function effectively as an individual, and as a member or leader in
PO8
diverse teams, and in multidisciplinary teams.
Communication: Communicate effectively on complex engineering activities with the
PO9 engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering
PO10 and management principles and apply these to one’s own work, as a member and leader in a team,
to manage projects and in multidisciplinary environments.

PO11 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
DEPARTMENT OF CSE (AI&ML)
Program Specific Outcomes(PSOs):

Graduates will be able to effectively apply foundational principles of mathematics, statistics,


PSO1 science, and engineering along with core concepts of artificial intelligence and machine learning to
analyze, model, and solve complex real-world problems in diverse computer science and
engineering domains.
Graduates will be able to effectively apply foundational principles of mathematics, statistics,
PSO2 science, and engineering along with core concepts of artificial intelligence and machine learning to
analyze, model, and solve complex real-world problem.

Bloom’s taxonomy Levels

[Link] – recalling relevant terminology, specific facts, or different procedures related to


information and/or course topics. At this level, a student can remember something, but may not really
understand it.
[Link] – the ability to grasp the meaning of information (facts, definitions, concepts, etc.) that
has been presented.
[Link] – being able to use previously learned information in different situations or in problem solving.
[Link] – the ability to break information down into its component parts. Analysis also refers to the
process of examining information in order to make conclusions regarding cause and effect, interpreting
motives, making inferences, or finding evidence to support statements/arguments.
[Link] – being able to judge the value of information and/or sources of information based on
personal values or opinions.
[Link] – the ability to creatively or uniquely apply prior knowledge and/or skills to produce new and
original thoughts, ideas, processes, etc. At this level, students are involved in creating their own thoughts
and ideas.
DEPARTMENT OF CSE (AI&ML)
COURSE OUTCOMES(COs):
On successful completion of this course, students should be able to:

Knowledge
CO. Level (Blooms
Course No. Course Outcomes (CO) Level)

Able to write the programs for solving real world


CO1 L3 – Apply
problems using Java OOP principles.
JAVA
PROGRAM Able to write programs using Exceptional Handling
CO2 approach. L4- Analyze
MING LAB

Able to write multithreaded applications. L5 – Evaluate


CO3
Able to write GUI programs using swing controls in
L4- Analyze
CO4 Java.

Course Program
Outcome Specific
Program Outcomes (PO)
s Outcomes
(CO) (PSO)
PO PO PO PO PO PO
PO1
2 3 4 5 6 7
PO8 PO9 PO10 PO11 PSO1 PSO2

CO 1 3 3 3 2 2 – – – 1 1 – 3 2

CO 2 3 2 2 2 2 – – – 1 – – 2 2

CO 3 3 3 3 2 2 – – – 2 – – 3 3

CO 4 2 2 3 2 3 – – – 2 2 – 2 3

AV G 2.75 2.5 2.75 2 2.25 – – – 1.5 1.5 – 2.5 2.5


Certificate
Certified that this is the Bonafide Record of the work done by

Mr./Ms. [Link] of

[Link] Year Semester for the Academic year

in the Laboratory

held on .

Faculty Incharge HOD-CSE(AI&ML)

Internal Examiner External Examiner


INDEX

Exp
Date Name of the Experiment Page No. Sign.
No.

1.

2.

3.

4.

5.

8.

9.
JAVA PROGRAMMING LAB SYLLABUS

List of Experiments:

1. Use Eclipse or Net bean platform and acquaint yourself with the various menus. Create a test project, add a
test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring
like renaming variables, methods, and classes. Try debug step by step with a small program of about 10 to 15
lines which contains at least one if else condition and a for loop.
2. Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance, Polymorphism and
Abstraction]
3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the usage of custom
exceptions in real time scenario.
4. Write a Java program on Random Access File class to perform different read and write operations.
5. Write a Java program to demonstrate the working of different collection classes. [Use package structure to
store multiple classes].
6. Write a program to synchronize the threads acting on the same object. [Consider the example of any
reservations like railway, bus, movie ticket booking, etc.]
7. Write a program to perform CRUD operations on the student table in a database using JDBC.
8. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and
for the +, -,*, % operations. Add a text field to display the result. Handle any possible exceptions like divided
by zero.
9. Write a Java program that handles all mouse events and shows the event name at the center of the window
when a mouse event is fired. [Use Adapter classes]

REFERENCE BOOKS:
1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson education.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.
4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.
Java Programming Lab HT No:

Introduction to Java Programming Lab:

Java is a high-level, object-oriented, platform-independent programming language


developed by Sun Microsystems in 1995 and currently maintained by Oracle Corporation. It is
designed to be simple, secure, robust, and portable, making it one of the most widely used
programming languages in the world.

Java programs are written once and can be executed on any platform that supports the Java
Virtual Machine (JVM), following the principle “Write Once, Run Anywhere (WORA)”.

FEATURES OF JAVA

1. Object-Oriented
Java follows object-oriented principles such as encapsulation, inheritance, polymorphism,
and abstraction.
2. Platform Independent
Java code is compiled into bytecode, which can run on any system with a JVM.
3. Simple and Easy to Learn
Java syntax is similar to C and C++, making it easier for beginners.
4. Secure
Java provides security features such as bytecode verification and runtime checking.
5. Robust
Java includes strong memory management and exception handling mechanisms.
6. Multithreaded
Java supports concurrent execution of multiple threads.
7. Portable
Java programs are not dependent on hardware or operating system.

JAVA PROGRAM EXECUTION PROCESS

1. Java source code is written using a text editor or IDE.


2. The Java compiler (javac) compiles the source code into bytecode.
3. The JVM interprets or executes the bytecode.
4. Output is displayed to the user.

APPLICATIONS OF JAVA

 Desktop Applications
 Web Applications
 Mobile Applications (Android)
 Enterprise Applications
 Scientific and Research Applications

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 1


Java Programming Lab HT No:

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 2


Java Programming Lab HT No:

Experiment – 1 Use Eclipse or Net bean platform and acquaint yourself with the various
menus. Create a test project, add a test class, and run it. See how you can use auto
suggestions, auto fill. Try code formatter and code refactoring like renaming variables,
methods, and classes. Try debug step by step with a small program of about 10 to 15 lines
which contains at least one if else condition and a for loop.

Aim:
To familiarize with Eclipse or NetBeans IDE, explore menus, create and run a Java
project, use auto suggestions, code formatter, refactoring, and debugging.

Software Required:
• Eclipse IDE or NetBeans IDE
• JDK 8 or above
• Windows/Linux OS

Procedure:
1. Open Eclipse or NetBeans IDE and observe Menu Bar, Toolbar, Project Explorer, Editor, and
Console.
2. Create a new Java project named TestProject.
3. Create a class TestProgram with main method.

Java Program:
public class TestProgram {

public static void main(String[] args) {


int sum = 0;

for (int i = 1; i <= 5; i++) {


if (i % 2 == 0) {
sum = sum + i;
}
}

[Link]("Sum of even numbers: " + sum);


}
}

Execution:
Run the program as Java Application.
Output:
Sum of even numbers: 6
Source Code Explanation:
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 3
Java Programming Lab HT No:

 Loop will run from i = 1 to i = 5.


 Total iterations = 5

Iteration-wise Calculation Table

Iteration 1

 i=1
 Condition check: 1 % 2 == 0 ❌ (False)
 sum remains 0

Iteration 2

 i=2
 Condition check: 2 % 2 == 0 ❌ (True)
 Calculation:

sum = sum + i;
sum = 0 + 2 = 2

 Updated sum = 2

Iteration 3

 i=3
 Condition check: 3 % 2 == 0 ❌ (False)
 sum remains 2

Iteration 4

 i=4
 Condition check: 4 % 2 == 0 ❌ (True)
 Calculation:

sum = sum + i;
sum = 2 + 4 = 6

 Updated sum = 6

Iteration 5

 i=5
 Condition check: 5 % 2 == 0 ❌ (False)
 sum remains 6

Step-by-Step Summary Table


Iteration i Value i % 2 == 0 Action Taken sum Value

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 4


Java Programming Lab HT No:

Iteration i Value i % 2 == 0 Action Taken sum Value

1 1 False No addition 0

2 2 True sum = 0 + 2 2

3 3 False No addition 2

4 4 True sum = 2 + 4 6

5 5 False No addition 6

Final Output
Sum of even numbers: 6

IDE Features:
1. Auto Suggestion:

 Type System. → press Ctrl + Space


 IDE automatically shows suggestions like:
o out
o println()
 Variables and methods are auto-completed.

2. Code Formatter: Ctrl + Shift + F


[Link]: Refactor → Rename

Rename Variable

 Right-click on variable sum


 Refactor → Rename
 Change name to total
 IDE updates all references automatically.

Rename Method / Class

 Right-click on class name


 Refactor → Rename
 Changes applied throughout the project.
 Prevents manual errors.

[Link]: Breakpoints, Step Into (F5), Step Over (F6)

Result:

The Java program was successfully created, executed, formatted, refactored, and debugged using
Eclipse/NetBeans IDE.
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 5
Java Programming Lab HT No:

Experiment 2. Write a Java program to demonstrate the OOP principles. [i.e.,


Encapsulation, Inheritance, Polymorphism and Abstraction]

1. Encapsulation

Encapsulation is the process of binding data (variables) and methods (functions) together
into a single unit called a class. It also involves hiding the internal details of an object and
allowing access only through well-defined interfaces.

In Java, encapsulation is achieved by:

 Declaring data members as private


 Providing public getter and setter methods to access and modify the data

Encapsulation improves data security, code maintainability, and controlled access to class
members.

Example:
A Student class with private variables name and age accessed using setName() and getName()
methods.

2. Inheritance

Inheritance is the mechanism in which one class acquires the properties and behaviors of
another class. The class that is inherited from is called the parent (super) class, and the class that
inherits is called the child (sub) class.

In Java, inheritance is implemented using the extends keyword.

Advantages of inheritance:

 Code reusability
 Reduced redundancy
 Easier maintenance
 Establishes a parent–child relationship

Example:
A Manager class inheriting methods from an Employee class.

3. Polymorphism

Polymorphism means one method, many forms. It allows the same method name to perform
different tasks based on the object that invokes it.

There are two types of polymorphism in Java:

1. Compile-time polymorphism (Method Overloading)


2. Runtime polymorphism (Method Overriding)
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 6
Java Programming Lab HT No:

In runtime polymorphism, a parent class reference is used to refer to a child class object, and
the method call is resolved at runtime.

Example:
A Shape reference calling the draw() method of a Circle object.

4. Abstraction

Abstraction is the process of hiding implementation details and showing only essential
features to the user. It focuses on what an object does, not how it does it.

In Java, abstraction is achieved using:

 Abstract classes
 Interfaces

An abstract class may contain:

 Abstract methods (without body)


 Concrete methods (with body)

Abstraction helps in:

 Reducing complexity
 Improving flexibility
 Enhancing security

Example:
An abstract class Vehicle with an abstract method start() implemented by the Bike class.

Program 2 a): Encapsulation


Aim:
To demonstrate Encapsulation in Java.

Program:
class encap {
// Private data members (data hiding)
private int id;
private String name;

// Setter method for id


public void setId(int id) {
[Link] = id;
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 7


Java Programming Lab HT No:

// Getter method for id


public int getId() {
return id;
}
// Setter method for name
public void setName(String name) {
[Link] = name;
}
// Getter method for name
public String getName() {
return name;
}
// Main method
public static void main(String[] args) {
encap obj = new encap();
// Setting values using setter methods
[Link](101);
[Link]("Java Student");
// Getting values using getter methods
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
}
}
Output:
ID: 101
Name: Java Student

Program 2b: Inheritance


Aim:
To demonstrate Inheritance in Java.

Program:
class Employee {
void display() {
[Link]("This is an Employee");
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 8
Java Programming Lab HT No:

}
}

class Manager extends Employee {


void show() {
[Link]("This is a Manager");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Manager m = new Manager();
[Link]();
[Link]();
}
}

Output:
This is an Employee
This is a Manager

2c: Polymorphism
Aim:
To demonstrate Polymorphism using method overriding.

Program:
class Shape {
void draw() {
[Link]("Drawing a Shape");
}
}

class Circle extends Shape {


void draw() {
[Link]("Drawing a Circle");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}

Output:
Drawing a Circle

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 9


Java Programming Lab HT No:

2d: Abstraction

Aim:
To demonstrate Abstraction using abstract class.

Program:
abstract class Vehicle {
abstract void start();
}

class Bike extends Vehicle {


void start() {
[Link]("Bike starts with kick");
}
}

public class AbstractionDemo {


public static void main(String[] args) {
Vehicle v = new Bike();
[Link]();
}
}

Output:
Bike starts with kick

Result:

Thus, the Java programs were successfully executed and the Object-Oriented
Programming (OOP) principles—Encapsulation, Inheritance, Polymorphism, and
Abstraction—were clearly demonstrated using separate programs. The output obtained
was correct and verified.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 10


Java Programming Lab HT No:

3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate
the usage of custom exceptions in real time scenario.

AIM
To write and execute a Java program that demonstrates the handling of checked
exceptions, unchecked exceptions, and user-defined (custom) exceptions using a real-time
scenario.
ALGORITHM

1. Start the program.


2. Create a user-defined exception class InsufficientBalanceException by extending the
Exception class.
3. Add a constructor in the custom exception class to pass the error message to the parent
class.
4. In the main program:
o Demonstrate a checked exception using file handling (IOException).
o Demonstrate an unchecked exception using division by zero
(ArithmeticException).
o Demonstrate a custom exception using a bank withdrawal scenario.
5. Handle all exceptions using appropriate try–catch blocks.
6. Display suitable messages for each exception.
7. Stop the program.

SOURCE CODE

Custom Exception Class

package exception;

public class InsufficientBalanceException extends Exception {

private static final long serialVersionUID = 1L;

public InsufficientBalanceException(String message) {


super(message);
}
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 11


Java Programming Lab HT No:

Main Program

package exception;

import [Link];
import [Link];
import [Link];

public class ExceptionDemo {

static void withdraw(double balance, double amount)


throws InsufficientBalanceException {

if (amount > balance) {


throw new InsufficientBalanceException(
"Withdrawal failed: Insufficient balance!");
}
[Link]("Withdrawal successful");
}

public static void main(String[] args) {

// Checked Exception
try {
File file = new File("[Link]");
FileReader fr = new FileReader(file);
[Link]();
} catch (IOException e) {
[Link]("Checked Exception handled");
}
// Unchecked Exception
try {
int x = 10 / 0;
[Link](x);
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 12
Java Programming Lab HT No:

} catch (ArithmeticException e) {
[Link]("Unchecked Exception handled");
}
// Custom Exception
try {
withdraw(5000, 7000);
} catch (InsufficientBalanceException e) {
[Link]([Link]());
}
}
}

EXPLANATION

 Checked Exception
File handling operations may cause IOException, which is a checked exception.
It must be handled using a try–catch block at compile time.
 Unchecked Exception
Division by zero causes ArithmeticException, which is an unchecked exception.
It occurs at runtime and is handled using a try–catch block.
 Custom Exception
InsufficientBalanceException is a user-defined exception created for a real-time banking
scenario.
It is thrown when the withdrawal amount exceeds the available balance.
 serialVersionUID
Used to maintain version control during serialization of the exception class.

SAMPLE OUTPUT

Checked Exception handled


Unchecked Exception handled
Withdrawal failed: Insufficient balance!
RESULT

Thus, the Java program to handle checked, unchecked, and custom exceptions was
successfully executed and verified.
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 13
Java Programming Lab HT No:

Experiment [Link] a Java program on Random Access File class to perform different read
and write operations.

AIM

To write and execute a Java program using the RandomAccessFile class to perform different
read and write operations on a file.

ALGORITHM

1. Start the program.


2. Create a RandomAccessFile object in read-write ("rw") mode.
3. Write different data values into the file using write methods.
4. Move the file pointer using the seek() method.
5. Read data from different positions using read methods.
6. Display the read values.
7. Close the file.
8. Stop the program.

SOURCE CODE

import [Link];
import [Link];

public class RandomAccessFileDemo {

public static void main(String[] args) {

try {
// Create RandomAccessFile in read-write mode
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");

// Writing data to the file


[Link](101); // Roll number
[Link]("Arun"); // Name
[Link](85.5); // Marks

[Link](102);
[Link]("Kavya");
[Link](92.0);

// Move file pointer to beginning


[Link](0);

// Reading first student record


[Link]("Student 1 Details:");
[Link]("Roll No: " + [Link]());
[Link]("Name : " + [Link]());
[Link]("Marks : " + [Link]());

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 14


Java Programming Lab HT No:

// Reading second student record


[Link]("\nStudent 2 Details:");
[Link]("Roll No: " + [Link]());
[Link]("Name : " + [Link]());
[Link]("Marks : " + [Link]());

[Link]();

} catch (IOException e) {
[Link]("File Error: " + [Link]());
}
}
}

EXPLANATION

 RandomAccessFile allows reading and writing at any position in a file.


 "rw" mode enables both read and write operations.
 writeInt(), writeUTF(), writeDouble() write data in binary format.
 seek(0) moves the file pointer to the beginning of the file.
 readInt(), readUTF(), readDouble() read data in the same order it was written.
 close() releases system resources.

SAMPLE OUTPUT

Student 1 Details:
Roll No: 101
Name : Arun
Marks : 85.5

Student 2 Details:
Roll No: 102
Name : Kavya
Marks : 92.0

RESULT

Thus, the Java program using the RandomAccessFile class to perform read and write
operations was successfully executed and verified.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 15


Java Programming Lab HT No:

Experiment [Link] a Java program to demonstrate the working of different collection


classes. [Use package structure to store multiple classes].

AIM

To write and execute a Java program to demonstrate the working of different Collection
classes such as List, Set, and Map using a package structure with multiple classes.

ALGORITHM

1. Start the program.


2. Create a package to store multiple Java classes.
3. Create a class to demonstrate List using ArrayList.
4. Create a class to demonstrate Set using HashSet.
5. Create a class to demonstrate Map using HashMap.
6. Create a main class to invoke all the above classes.
7. Add elements to each collection.
8. Display the elements stored in List, Set, and Map.
9. Stop the program.

PACKAGE NAME

collectionsdemo

CLASS 1: [Link]

(Demonstrates ArrayList)

package collectionsdemo;

import [Link];

public class ListDemo {

public void showList() {


ArrayList<String> list = new ArrayList<>();

[Link]("Java");
[Link]("Python");
[Link]("C++");

[Link]("ArrayList Elements:");
for (String item : list) {
[Link](item);
}
}
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 16


Java Programming Lab HT No:

CLASS 2: [Link]

(Demonstrates HashSet)

package collectionsdemo;

import [Link];

public class SetDemo {

public void showSet() {


HashSet<Integer> set = new HashSet<>();

[Link](10);
[Link](20);
[Link](10); // Duplicate not allowed

[Link]("\nHashSet Elements:");
for (int num : set) {
[Link](num);
}
}
}

CLASS 3: [Link]

(Demonstrates HashMap)

package collectionsdemo;

import [Link];
import [Link];

public class MapDemo {

public void showMap() {


HashMap<Integer, String> map = new HashMap<>();

[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");

[Link]("\nHashMap Elements:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 17


Java Programming Lab HT No:

}
}

CLASS 4: [Link]

(Main Class)

package collectionsdemo;

public class CollectionDemoMain {

public static void main(String[] args) {

ListDemo listObj = new ListDemo();


SetDemo setObj = new SetDemo();
MapDemo mapObj = new MapDemo();

[Link]();
[Link]();
[Link]();
}
}

ListDemo (ArrayList Program)

The ListDemo program demonstrates the use of the ArrayList class from the Java
Collections Framework. It creates an ArrayList to store a group of string elements and performs
basic operations such as adding elements and displaying them. The program shows that an
ArrayList allows duplicate elements, maintains insertion order, and supports dynamic resizing. An
enhanced for-loop is used to traverse and print all the elements stored in the list.

SetDemo (HashSet Program)

The SetDemo program illustrates the working of the HashSet class. It creates a HashSet to
store integer values and adds elements to it, including a duplicate value. The program
demonstrates that HashSet does not allow duplicate elements and does not maintain any specific
order of insertion. The elements stored in the set are displayed using an enhanced for-loop.

MapDemo (HashMap Program)

The MapDemo program demonstrates the use of the HashMap class, which stores data in
the form of key–value pairs. In this program, integer keys are mapped to string values. It shows
how elements are inserted using the put() method and how both keys and values can be retrieved
using the entrySet() method. The program also highlights that HashMap does not maintain any
insertion order.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 18


Java Programming Lab HT No:

CollectionDemoMain (Main Program)

The CollectionDemoMain program acts as the main driver class that brings together all the
collection demonstrations. It creates objects of ListDemo, SetDemo, and MapDemo classes and
invokes their respective methods. This program shows how multiple classes stored in the same
package can work together to demonstrate different collection.

HOW TO RUN IN ECLIPSE

1. Create a Java Project


2. Inside src, create a package named:
3. collectionsdemo
4. Create four classes with the exact names above
5. Paste corresponding code
6. Run [Link]

SAMPLE OUTPUT

ArrayList Elements:
Java
Python
C++

HashSet Elements:
20
10

HashMap Elements:
1 : Apple
2 : Banana
3 : Orange

(Order may vary for Set and Map)

KEY POINTS

 ArrayList → Allows duplicates, maintains insertion order


 HashSet → Does not allow duplicates
 HashMap → Stores data as key–value pairs
 Package structure improves modularity and readability

RESULT

Thus, the Java program to demonstrate the working of different Collection classes using a
package structure was successfully executed and the output was verified.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 19


Java Programming Lab HT No:

Experiment 6. Write a program to synchronize the threads acting on the same object.
[Consider the example of any reservations like railway, bus, movie ticket booking, etc.]

AIM

To synchronize multiple threads acting on the same object to avoid inconsistent results during
ticket booking.

ALGORITHM

1. Initialize total available seats


2. Create synchronized method for booking
3. Check seat availability
4. Deduct seats if available
5. Display success/failure message
6. Create multiple threads
7. Pass shared object to threads
8. Start threads
9. Ensure only one thread executes at a time
10. Stop the program.

Concept

When multiple threads try to access the same resource (like available tickets), it may cause race
conditions.

Solution: Use synchronized method/block to allow only one thread at a time.

PROGRAM: Ticket Reservation using Synchronization

CLASS 1: [Link]
class Reservation {

int availableSeats = 5;

// synchronized method
public synchronized void bookTicket(String name, int seats) {

[Link](name + " is trying to book " + seats + " seats");

if (availableSeats >= seats) {


[Link]("Booking successful for " + name);
availableSeats -= seats;
[Link]("Seats left: " + availableSeats);

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 20


Java Programming Lab HT No:

} else {
[Link]("Booking failed for " + name + " (Not enough seats)");
}
}
}

CLASS 2: [Link]
class UserThread extends Thread {

Reservation reservation;
String userName;
int seatsRequired;

public UserThread(Reservation reservation, String userName, int seatsRequired) {


[Link] = reservation;
[Link] = userName;
[Link] = seatsRequired;
}

public void run() {


[Link](userName, seatsRequired);
}
}

CLASS 3: Main Class


public class SynchronizationDemo {

public static void main(String[] args) {

Reservation obj = new Reservation();

UserThread t1 = new UserThread(obj, "Alice", 3);


UserThread t2 = new UserThread(obj, "Bob", 4);

[Link]();
[Link]();
}
}

Sample Output
Alice is trying to book 3 seats
Booking successful for Alice
Seats left: 2
Bob is trying to book 4 seats
Booking failed for Bob (Not enough seats)

RESULT

Thus, the Java program to synchronize multiple threads acting on the same object
using a ticket reservation system was successfully executed.
Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 21
Java Programming Lab HT No:

Experiment 7. Write a program to perform CRUD operations on the student table in


a database using JDBC.

AIM

To write a Java program to perform CRUD operations (Create, Read, Update, Delete) on a
Student table using JDBC.

ALGORITHM

1. Start the program


2. Load JDBC driver
3. Establish database connection
4. Create statement
5. Execute INSERT query
6. Execute SELECT query and display records
7. Execute UPDATE query
8. Execute DELETE query
9. Close connection
10. Stop the program

Step 1: Create Database & Table (MySQL)

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE student (


id INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);

PROGRAM: JDBC CRUD Operations

CLASS: [Link]
import [Link].*;

public class StudentCRUD {

static final String URL = "jdbc:mysql://localhost:3306/studentdb";


static final String USER = "root";
static final String PASSWORD = "root";

public static void main(String[] args) {

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 22


Java Programming Lab HT No:

try {
// Step 1: Load Driver
[Link]("[Link]");

// Step 2: Establish Connection


Connection con = [Link](URL, USER, PASSWORD);

// Step 3: Create Statement


Statement stmt = [Link]();

// � CREATE (Insert)
String insertQuery = "INSERT INTO student VALUES (1, 'Ravi', 90)";
[Link](insertQuery);
[Link]("Record Inserted");

// � READ (Select)
String selectQuery = "SELECT * FROM student";
ResultSet rs = [Link](selectQuery);

[Link]("\nStudent Records:");
while ([Link]()) {
[Link]([Link]("id") + " " +
[Link]("name") + " " +
[Link]("marks"));
}

// � UPDATE
String updateQuery = "UPDATE student SET marks = 95 WHERE id = 1";
[Link](updateQuery);
[Link]("\nRecord Updated");

// � DELETE
String deleteQuery = "DELETE FROM student WHERE id = 1";
[Link](deleteQuery);
[Link]("Record Deleted");

// Step 4: Close Connection


[Link]();

} catch (Exception e) {
[Link](e);
}
}
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 23


Java Programming Lab HT No:

Sample Output:

Record Inserted

Student Records:
1 Ravi 90

Record Updated
Record Deleted

RESULT

Thus, the Java program to perform CRUD operations on the Student table using JDBC
was executed successfully.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 24


Java Programming Lab HT No:

Experiment 8. Write a Java program that works as a simple calculator. Use a grid
layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divided by zero.

AIM

To develop a Java program for a simple calculator using Grid Layout with buttons for digits and
operations (+, -, *, %) and a text field to display results, handling exceptions like division by zero.

ALGORITHM

1. Start
2. Create JFrame and JTextField
3. Create buttons for digits and operators
4. Arrange buttons using GridLayout
5. Add ActionListener to buttons
6. If digit → append to text field
7. If operator → store first number and operator
8. If "=" → perform calculation
9. Handle divide-by-zero exception
10. Display result
11. If "C" → clear text field
12. Stop

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 25


Java Programming Lab HT No:

PROGRAM: Program: Simple Calculator using GridLayout


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

public class Calculator extends JFrame implements ActionListener {

JTextField tf;
String operator = "";
double num1 = 0, num2 = 0, result = 0;

public Calculator() {

setTitle("Simple Calculator");

// Text Field
tf = new JTextField();
[Link](new Font("Arial", [Link], 20));
add(tf, [Link]);

// Panel with GridLayout


JPanel panel = new JPanel();
[Link](new GridLayout(5, 4, 5, 5));

// Buttons
String buttons[] = {
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0","%","=","+",
"C"
};

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 26


Java Programming Lab HT No:

for (String text : buttons) {


JButton btn = new JButton(text);
[Link](new Font("Arial", [Link], 16));
[Link](this);
[Link](btn);
}

add(panel);

setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {

String cmd = [Link]();

try {
// If number
if ([Link]("[0-9]")) {
[Link]([Link]() + cmd);
}

// Operators
else if ([Link]("[+\\-*/%]")) {
num1 = [Link]([Link]());
operator = cmd;
[Link]("");
}

// Equals
else if ([Link]("=")) {

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 27


Java Programming Lab HT No:

num2 = [Link]([Link]());

switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/":
if (num2 == 0)
throw new ArithmeticException("Divide by zero");
result = num1 / num2;
break;
case "%": result = num1 % num2; break;
}

[Link]([Link](result));
}

// Clear
else if ([Link]("C")) {
[Link]("");
}

} catch (ArithmeticException ex) {


[Link]("Error: Divide by 0");
} catch (Exception ex) {
[Link]("Error");
}
}

public static void main(String[] args) {


new Calculator();
}
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 28


Java Programming Lab HT No:

Sample Output:

User clicks: 5 + 3 = → Output: 8

User clicks: 9 / 0 = → Output: Error: Divide by 0

RESULT

Thus, the Java program for a simple calculator using GridLayout was successfully
implemented. The calculator performs arithmetic operations and handles exceptions like division
by zero effectively.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 29


Java Programming Lab HT No:

Experiment 9. Write a Java program that handles all mouse events and shows the
event name at the center of the window when a mouse event is fired. [Use Adapter classes]

AIM

To write a Java program that handles mouse events using Adapter classes and displays the event
name at the center of the window.

ALGORITHM

1. Start
2. Create JFrame
3. Initialize message string
4. Create adapter class extending MouseAdapter
5. Override required mouse event methods
6. Update message for each event
7. Call repaint()
8. Override paint() method
9. Display message at center
10. Run the program
11. Stop

Mouse Events Handled

Event Method Description

mouseClicked() Mouse click

mousePressed() Mouse button pressed

mouseReleased() Mouse button released

mouseEntered() Mouse enters window

mouseExited() Mouse exits window

mouseMoved() Mouse movement

mouseDragged() Mouse drag

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 30


Java Programming Lab HT No:

PROGRAM: Mouse Events using Adapter Classes


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

public class MouseEventDemo extends JFrame {

String msg = "No Event";

public MouseEventDemo() {

setTitle("Mouse Event Demo");


setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Add Mouse Adapter


addMouseListener(new MyMouseAdapter());
addMouseMotionListener(new MyMouseAdapter());

setVisible(true);
}

// Adapter Class
class MyMouseAdapter extends MouseAdapter {

public void mouseClicked(MouseEvent e) {


msg = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent e) {


msg = "Mouse Pressed";
repaint();
}

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 31


Java Programming Lab HT No:

public void mouseReleased(MouseEvent e) {


msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


msg = "Mouse Exited";
repaint();
}
public void mouseMoved(MouseEvent e) {
msg = "Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e) {
msg = "Mouse Dragged";
repaint();
}
}

// Display text in center


public void paint(Graphics g) {
[Link](g);

[Link](new Font("Arial", [Link], 20));

FontMetrics fm = [Link]();
int x = (getWidth() - [Link](msg)) / 2;
int y = getHeight() / 2;

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 32


Java Programming Lab HT No:

[Link](msg, x, y);
}

public static void main(String[] args) {


new MouseEventDemo();
}
}

Sample Output:

 Click mouse → Mouse Clicked

 Move mouse → Mouse Moved

 Drag mouse → Mouse Dragged

 Enter window → Mouse Entered

 Exit window → Mouse Exited

RESULT

The Java program to handle all mouse events using Adapter classes was successfully
executed.

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 33


Java Programming Lab HT No:

Dept of CSE (AI&ML) Bharat Institute of Engineering and Technology Page 34

You might also like