Java Lab Manual Updated
Java Lab Manual Updated
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
DEPARTMENT OF CSE
(ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING)
BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
Ibrahimpatnam - 501 510, Hyderabad
DEPARTMENT OF CSE (AI&ML)
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
DEPARTMENT OF CSE
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.
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):
Knowledge
CO. Level (Blooms
Course No. Course Outcomes (CO) Level)
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
Mr./Ms. [Link] of
in the Laboratory
held on .
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:
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.
APPLICATIONS OF JAVA
Desktop Applications
Web Applications
Mobile Applications (Android)
Enterprise Applications
Scientific and Research Applications
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 {
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:
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
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:
Rename Variable
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:
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.
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.
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.
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.
Abstract classes
Interfaces
Reducing complexity
Improving flexibility
Enhancing security
Example:
An abstract class Vehicle with an abstract method start() implemented by the Bike class.
Program:
class encap {
// Private data members (data hiding)
private int id;
private String name;
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:
}
}
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");
}
}
Output:
Drawing a Circle
2d: Abstraction
Aim:
To demonstrate Abstraction using abstract class.
Program:
abstract class Vehicle {
abstract void start();
}
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.
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
SOURCE CODE
package exception;
Main Program
package exception;
import [Link];
import [Link];
import [Link];
// 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
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
SOURCE CODE
import [Link];
import [Link];
try {
// Create RandomAccessFile in read-write mode
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link](102);
[Link]("Kavya");
[Link](92.0);
[Link]();
} catch (IOException e) {
[Link]("File Error: " + [Link]());
}
}
}
EXPLANATION
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.
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
PACKAGE NAME
collectionsdemo
CLASS 1: [Link]
(Demonstrates ArrayList)
package collectionsdemo;
import [Link];
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("ArrayList Elements:");
for (String item : list) {
[Link](item);
}
}
}
CLASS 2: [Link]
(Demonstrates HashSet)
package collectionsdemo;
import [Link];
[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];
[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");
[Link]("\nHashMap Elements:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
}
}
CLASS 4: [Link]
(Main Class)
package collectionsdemo;
[Link]();
[Link]();
[Link]();
}
}
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.
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.
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.
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.
SAMPLE OUTPUT
ArrayList Elements:
Java
Python
C++
HashSet Elements:
20
10
HashMap Elements:
1 : Apple
2 : Banana
3 : Orange
KEY POINTS
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.
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
Concept
When multiple threads try to access the same resource (like available tickets), it may cause race
conditions.
CLASS 1: [Link]
class Reservation {
int availableSeats = 5;
// synchronized method
public synchronized void bookTicket(String name, int seats) {
} else {
[Link]("Booking failed for " + name + " (Not enough seats)");
}
}
}
CLASS 2: [Link]
class UserThread extends Thread {
Reservation reservation;
String userName;
int seatsRequired;
[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:
AIM
To write a Java program to perform CRUD operations (Create, Read, Update, Delete) on a
Student table using JDBC.
ALGORITHM
USE studentdb;
CLASS: [Link]
import [Link].*;
try {
// Step 1: Load Driver
[Link]("[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");
} catch (Exception e) {
[Link](e);
}
}
}
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.
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
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]);
// Buttons
String buttons[] = {
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0","%","=","+",
"C"
};
add(panel);
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
try {
// If number
if ([Link]("[0-9]")) {
[Link]([Link]() + cmd);
}
// Operators
else if ([Link]("[+\\-*/%]")) {
num1 = [Link]([Link]());
operator = cmd;
[Link]("");
}
// Equals
else if ([Link]("=")) {
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]("");
}
Sample Output:
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.
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
public MouseEventDemo() {
setVisible(true);
}
// Adapter Class
class MyMouseAdapter extends MouseAdapter {
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](msg)) / 2;
int y = getHeight() / 2;
[Link](msg, x, y);
}
Sample Output:
RESULT
The Java program to handle all mouse events using Adapter classes was successfully
executed.