DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
MACHINE LEARNING
II [Link] II SEM AIML (R22)
JAVA PROGRAMMING LAB MANUAL
(ACADEMIC YEAR 2025-2026)
[Link].1. Test Project
Aim:
Use eclipse or Netbean platform and acquaint 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.
Source Code:
Sample_Program.java
/* Sample java program to check given number is prime or not*/
//Importing packages import [Link];
import [Link];
// Creating Class
class Sample_Program
{
// main method
public static void main(String args[])
{ int i,count=0,n;
// creating scanner object
Scanner sc=new Scanner([Link]);
// get input number from user
[Link]("Enter Any Number : "); n=[Link]();
// logic to check prime or not
for(i=1;i<=n;i++)
{
if(n%i==0) {
count++;
}
}
if(count==2)
[Link](n+" is prime");
else
[Link](n+" is not prime");
}
}
Output:
[Link].2. Demonstration of OOP Principles
Aim:
Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance,
Polymorphism and Abstraction]
Source Code:
[Link]
/* Encapsulation:
The fields of the class are private and accessed through
getter and setter methods.*/
class Person
{
// private fields private String name;
private int age;
// constructor
public Person(String name, int age)
{
[Link] = name; [Link] = age;
}
// getter and setter methods public String getName()
{
return name;
}
public void setName(String name)
{ [Link] = name;
}
public int getAge()
{ return age;
}
public void setAge(int age)
{ [Link] = age;
}
/* Abstraction:
The displayInfo() method provides a simple interface to
interact with the object.*/
public void displayInfo()
{ [Link]("Name: " + name);
[Link]("Age: " + age);
}
}
/* Inheritance:
Employee is a subclass of Person, inheriting its properties
and methods.*/
class Employee extends Person
{
// private field private double salary;
// constructor
public Employee(String name, int age, double salary)
{ super(name, age);
[Link] = salary;
}
// getter and setter methods public double getSalary()
{
return salary;
}
public void setSalary(double salary)
{ [Link] = salary;
}
/* Polymorphism:
Overriding the displayInfo() method to provide a specific
implementation for Employee.*/
@Override
public void displayInfo()
{ [Link]();
[Link]("Salary: " + salary);
}
}
public class OopPrinciplesDemo
{
public static void main(String[] args)
{
// Demonstrating encapsulation and abstraction Person
person = new Person("Madhu", 30);
[Link]("Person Info:");
[Link]();
[Link]("====================");
// Demonstrating inheritance and polymorphism
Employee employee = new Employee("Naveen", 26, 50000);
[Link]("Employee Info:");
[Link]();
}
}
Output:
[Link].3. Exceptions
Aim:
Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the
usage of custom exceptions in real time scenario.
Source Code:
[Link]
import [Link];
import [Link];
import [Link];
// Custom Exception
class InvalidAgeException extends Exception
{ public InvalidAgeException(String message)
{
super(message);
}
}
public class ExceptionsDemo
{
// Method to demonstrate custom exception
public static void register(String name, int age) throws
InvalidAgeException
{
if (age < 18)
{
throw new InvalidAgeException("User must be at least 18 years old.");
} else {
[Link]("Registration successful for user: " + name);
}
}
public static void main(String[] args)
{
//Handling Checked Exception try
{
File file = new File("[Link]");
// This line can throw FileNotFoundException FileReader fr = new
FileReader(file);
} catch (FileNotFoundException e)
{ [Link]("File not found: " +
[Link]());
}
//Handling Unchecked Exception try
{
int[] arr = {1, 2, 3};
// Accessing an out-of-bound index [Link](arr[6]);
} catch (ArrayIndexOutOfBoundsException e)
{ [Link]("Array index out of bounds: " +
[Link]());
}
// Finally block to perform cleanup operations finally
{
[Link]("Cleanup operations can be performed here.");
}
// Demonstrate custom exception handling
[Link]("Demonstrating Custom Exception:");
try
{
// Invalid age for registration register("Madhu", 17);
} catch (InvalidAgeException e)
{
[Link]("Custom Exception Caught: " +
[Link]());
}
}
}
Output:
[Link].4. Random Access File
Aim:
Write a Java program on Random Access File class to perform different read and write operations.
Source Code:
[Link]
import [Link].*;
public class RandomAccessFileExample
{ public static void main(String[] args)
{
try
{
// Move the file pointer to the beginning of the file
[Link](0);
// Read data from the file
String readData1 = [Link]();
String readData2 = [Link]();
[Link]("Data read from file:");
[Link](readData1);
[Link](readData2);
// Move the file pointer to the ending of the file
[Link]([Link]());
// Append new data to the file String newData = "Java!";
[Link](newData);
// Move the file pointer to the beginning of the file
[Link](0);
// Read data from the file again after appending readData1 =
[Link]();
readData2 = [Link]();
String readData3 = [Link]();
[Link]("Data read from file after appending:");
[Link](readData1);
[Link](readData2);
[Link](readData3);
// Close the file [Link]();
} catch (IOException e)
{ [Link]("An error occurred: " +
[Link]());
[Link]();
}
}
}
Output:
[Link].5. Collection Classes
Aim:
Write a Java program to demonstrate the working of different collection classes. [Use package structure
to store multiple classes].
Source Code:
[Link]
package collections;
import [Link];
public class ListExample
{
public static void main(String[] args)
{ ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
// to display
[Link]("List Example:");
for (String fruit : list)
{
[Link](fruit);
}
}
}
[Link]
package collections;
import [Link];
public class SetExample {
public static void main(String[] args)
{ HashSet<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple");
// This won't be added since sets don't allow duplicates
// To display
[Link]("Set Example:");
for (String fruit : set)
{
[Link](fruit);
}
}
}
[Link]
package collections; import [Link];
public class MapExample
{
public static void main(String[] args)
{ HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");
// To display
[Link]("Map Example:");
for ([Link]<Integer, String> entry : [Link]())
{
[Link]([Link]() + ": " + [Link]());
}
}
}
[Link]
package collections;
public class CollectionsDemo
{
public static void main(String[] args)
{ [Link](args);
[Link](args);
[Link](args);
}
}
Output:
[Link]. 6. Threads
Aim:
Write a Java program to synchronize the threads acting on the same object. Consider the example of a
railway reservation system where multiple users try to book tickets simultaneously.
Source Code:
[Link]
import [Link].*;
class TicketBooking {
private int availableSeats = 2;
synchronized void bookTicket(String passengerName, int seatsRequested)
{
[Link](passengerName + " is trying to book " + seatsRequested
+ " seat(s).");
if (seatsRequested <= availableSeats)
{
[Link]("Booking confirmed for " + passengerName);
availableSeats -= seatsRequested;
} else {
[Link]("Sorry, not enough seats available for " +
passengerName);
}
[Link]("Remaining seats: " + availableSeats);
}
}
class Passenger extends Thread
{
TicketBooking bookingSystem;
String name;
int seats;
Passenger(TicketBooking bookingSystem, String name, int seats)
{
[Link] = bookingSystem;
[Link] = name;
[Link] = seats;
}
public void run()
{
[Link](name, seats);
}
}
public class RailwayReservation
{
public static void main(String[] args)
{
TicketBooking system = new TicketBooking();
Passenger p1 = new Passenger(system, "Alice", 1);
Passenger p2 = new Passenger(system, "Bob", 1);
Passenger p3 = new Passenger(system, "Charlie", 1);
[Link]();
[Link]();
[Link]();
}
}
Output:
Alice is trying to book 1 seat(s).
Booking confirmed for Alice
Remaining seats: 1
Bob is trying to book 1 seat(s).
Booking confirmed for Bob
Remaining seats: 0
Charlie is trying to book 1 seat(s).
Sorry, not enough seats available for Charlie
Remaining seats: 0
[Link]. 7. CRUD (Create, Read, Update, Delete) Operations
Aim:
Write a program to perform CRUD ( C r e a t e , R e a d , U p d a t e , D e l e t e ) operations on the
student table in a database using JDBC.
Source Code:
[Link]
import [Link].*;
import [Link];
public class InsertData
{
public static void main(String[] args)
{
try
{
// to create connection with database
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table Scanner sc = new
Scanner([Link]);
[Link]("Inserting Data into student
table : ");
[Link](" ")
;
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute insert query [Link]("insert into student
values("+sid+",'"+sname+"','"+saddr+"')");
[Link]("Data inserted successfully into student table");
[Link]();
[Link]();
} catch (SQLException err)
{
[Link]("ERROR: " + err);
} catch (Exception err)
{ [Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link]; public class UpdateData
{
public static void main(String[] args)
{
try
{
// to create connection with database
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table Scanner sc = new
Scanner([Link]);
[Link]("Update Data in student table :
");
[Link](" ")
;
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute update query [Link]("update student set
s_name='"+sname+"',s_address = '"+saddr+"' where s_id = "+sid);
[Link]("Data updated successfully");
[Link]();
[Link]();
} catch (SQLException err)
{ [Link]("ERROR: " + err);
} catch (Exception err)
{ [Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link];
public class DeleteData
{
public static void main(String[] args)
{ try {
// to create connection with database
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table Scanner sc = new
Scanner([Link]);
[Link]("Delete Data from student table
: ");
[Link](" ")
;
"+sid);
[Link]("Enter student id : ");
int sid = [Link]();
// to execute delete query [Link]("delete from student where s_id =
[Link]("Data deleted successfully");
[Link]();
[Link]();
}
catch (SQLException err)
{
[Link]("ERROR: " + err);
}
catch (Exception err)
{
[Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link]; public class DisplayData
{
public static void main(String[] args)
{
try
{
// to create connection with database
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost/mydb", "root", "");
Statement s = [Link]();
// To display the data from the student table ResultSet rs =
[Link]("select * from
student");
if (rs != null) {
[Link]("SID \t STU_NAME \t ADDRESS");
[Link](" ")
;
while ([Link]())
{
[Link]([Link](1) +" \t "+ [Link](2)+ " \t
"+[Link](3));
[Link](" ")
;
}
[Link]();
[Link]();
}
}
catch (SQLException err)
{
[Link]("ERROR: " + err);
}
catch (Exception err)
{
[Link]("ERROR: " + err);
}
}
}
Output:
Alice is trying to book 1 seat(s).
Booking confirmed for Alice
Remaining seats: 1
Bob is trying to book 1 seat(s).
Booking confirmed for Bob
Remaining seats: 0
Charlie is trying to book 1 seat(s).
Sorry, not enough seats available for Charlie
Remaining seats: 0
[Link].8. Simple Calculator
Aim:
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.
Source Code:
[Link]
/* Program to create a Simple Calculator */
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener
{
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel; public void init()
{
nPanel=new Panel();
T1=new TextField(30);
[Link](new FlowLayout([Link]));
[Link](T1);
CPanel=new Panel();
[Link]([Link]);
[Link](new GridLayout(5,5,3,3));
for(int i=0;i<10;i++)
{
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
[Link](this);
for(int i=0;i<10;i++)
{
[Link](NumButtons[i]);
}
[Link](Add);
[Link](Sub);
[Link](Mul);
[Link](Div);
[Link](EQ);
SPanel=new Panel();
[Link](new FlowLayout([Link]));
[Link]([Link]);
[Link](clear);
for(int i=0;i<10;i++)
{ NumButtons[i].addActionListener(this);
}
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](new BorderLayout());
add(nPanel,[Link]);
add(CPanel,[Link]);
add(SPanel,[Link]);
}
public void actionPerformed(ActionEvent ae)
{ String str=[Link] ();
char ch=[Link](0);
if([Link](ch))
[Link]([Link]()+str);
else
if([Link]("+"))
{ num1=[Link] ([Link]());
Operation='+';
[Link] ("");
}
if([Link]("-"))
{ num1=[Link]([Link]());
Operation='-';
[Link]("");
}
if([Link]("*"))
{ num1=[Link]([Link]());
Operation='*';
[Link]("");
}
if([Link]("/"))
{ num1=[Link]([Link]());
Operation='/';
[Link]("");
}
if([Link]("%"))
{ num1=[Link]([Link]());
Operation='%';
[Link]("");
}
if([Link]("="))
{ num2=[Link]([Link]());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e)
{ result=num2;
[Link](this,"Divided by zero");
}
break;
}
[Link](""+result);
}
if([Link]("clear"))
{
[Link]("");
}
}
}
Output:
[Link]. 9. Handling Mouse Events
Aim:
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]
Source Code:
[Link]
import [Link].*; import [Link].*;
import [Link].*;
import [Link].*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout([Link]));
l1 = new JLabel();
Font f = new Font("Verdana", [Link], 20);
[Link](f);
[Link]([Link]);
add(l1); addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
[Link]("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
[Link]("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
[Link]("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
[Link]("Mouse Clicked");
}
public static void main(String[] args)
{
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output: