JAVA LAB MANUAL
LIST OF EXPERIMENTS:
1) Preparing and prac ce – Installa on of Java so ware, study of any Integrated
developmentenvironment, sample programs on operator precedence and associa vity, class and
package concept, scope concept, control structures, constructors and destructors. Learn to
compile, debug and execute java programs.
Experiment 1: Preparing and Prac ce
Aim:
To install Java so ware, study an Integrated Development Environment (IDE), and prac ce with
sample programs on operator precedence, associa vity, class and package concepts, scope, control
structures, constructors, and destructors. Learn how to compile, debug, and execute Java programs.
Program:
1. Operator Precedence and Associa vity:
public class OperatorPrecedence {
public sta c void main(String[] args) {
int result = 10 + 5 * 2;
System.out.println("Result: " + result);
2. Class and Package Concept:
package myPackage;
public class MyClass {
int x;
public MyClass(int y) {
x = y;
}
JAVA LAB MANUAL
public void display() {
System.out.println("Value of x: " + x);
Result:
Programs successfully demonstrate operator precedence, class, and package concepts.
2) a) Write Java program(s) to display n prime numbers.
Experiment 2: Prime Numbers and Matrix Mul plica on
Aim :
Write a Java program to display 'n' prime numbers.
Program :
import java.u l.Scanner;
public class PrimeNumbers {
public sta c void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int count = 0, num = 2;
while (count < n) {
if (isPrime(num)) {
System.out.println(num);
JAVA LAB MANUAL
count++;
num++;
public sta c boolean isPrime(int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
return true;
Result :
Program displays 'n' prime numbers.
b) Write Java program(s) to mul ply two matrices.
Aim :
Write a Java program to mul ply two matrices.
Program :
import java.u l.Scanner;
public class MatrixMul plica on {
public sta c void main(String[] args) {
JAVA LAB MANUAL
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix:");
int row = sc.nextInt();
int col = sc.nextInt();
int[][] matrix1 = new int[row][col];
int[][] matrix2 = new int[row][col];
int[][] product = new int[row][col];
System.out.println("Enter the elements of matrix1:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix1[i][j] = sc.nextInt();
System.out.println("Enter the elements of matrix2:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix2[i][j] = sc.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
product[i][j] = matrix1[i][j] * matrix2[i][j];
System.out.println("Product of the matrices:");
JAVA LAB MANUAL
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(product[i][j] + "\t");
System.out.println();
Result :
Matrix mul plica on performed successfully.
3)a) Write a Java program to create a student class with following fields
i. Hall cket number
ii. Student Name
iii. Department Create ‘n’ number of Student objects where ‘n’ value is passed as input to
constructor.
Experiment 3: Student Class and String Comparison
Aim :
Write a Java program to create a student class with fields: Hall cket number, Student Name, and
Department. Create ‘n’ Student objects where ‘n’ is passed to the constructor.
Program :
import java.u l.Scanner;
class Student {
String hallTicket, name, department;
JAVA LAB MANUAL
public Student(String hallTicket, String name, String department) {
this.hallTicket = hallTicket;
this.name = name;
this.department = department;
public void display() {
System.out.println("Hall Ticket: " + hallTicket);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
public class StudentTest {
public sta c void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter Hall Ticket: ");
String hallTicket = sc.next();
System.out.print("Enter Name: ");
String name = sc.next();
System.out.print("Enter Department: ");
String department = sc.next();
students[i] = new Student(hallTicket, name, department);
System.out.println("\nDisplaying student details:");
JAVA LAB MANUAL
for (Student s : students) {
s.display();
Result :
Student objects successfully created and displayed.
b) Write a Java program to demonstrate String comparison using == and equals method. 4) Write a
program in JAVA to demonstrate the method and constructor overloading.
Aim:
Write a Java program to demonstrate String comparison using `==` and `equals()` method.
Program :
public class StringComparison {
public sta c void main(String[] args) {
String str1 = "Hello";
String str2 = new String("Hello");
// Using ==
if (str1 == str2) {
System.out.println("str1 and str2 are equal (==)");
} else {
System.out.println("str1 and str2 are NOT equal (==)");
// Using equals()
JAVA LAB MANUAL
if (str1.equals(str2)) {
System.out.println("str1 and str2 are equal (equals)");
} else {
System.out.println("str1 and str2 are NOT equal (equals)");
Result :
Program demonstrates the difference between `==` and `equals()` for string comparison.
4) Write a program in JAVA to demonstrate the method and constructor overloading.
Experiment 4: Method and Constructor Overloading
Aim:
Write a Java program to demonstrate method and constructor overloading.
Program:
class OverloadDemo {
void display(int a) {
System.out.println("Integer: " + a);
void display(double a) {
System.out.println("Double: " + a);
OverloadDemo() {
JAVA LAB MANUAL
System.out.println("Default constructor");
OverloadDemo(int a) {
System.out.println("Parameterized constructor with integer: " + a);
OverloadDemo(String s) {
System.out.println("Parameterized constructor with string: " + s);
public class OverloadingTest {
public sta c void main(String[] args) {
OverloadDemo obj1 = new OverloadDemo();
OverloadDemo obj2 = new OverloadDemo(10);
OverloadDemo obj3 = new OverloadDemo("Hello");
obj1.display(5);
obj1.display(5.5);
Result:
Program demonstrates method and constructor overloading successfully.
5) a) Demonstrate the implementa on of inheritance (mul level, hierarchical and mul ple) by
using extend and implement keywords.
Experiment 5
JAVA LAB MANUAL
a) Aim:
To demonstrate the implementa on of inheritance (mul level, hierarchical, and mul ple) using
`extends` and `implements` keywords.
Program:
// Mul level Inheritance
class A {
void showA() {
System.out.println("Class A method");
class B extends A {
void showB() {
System.out.println("Class B method");
class C extends B {
void showC() {
System.out.println("Class C method");
// Hierarchical Inheritance
class X {
void showX() {
System.out.println("Class X method");
}
JAVA LAB MANUAL
class Y extends X {
void showY() {
System.out.println("Class Y method");
class Z extends X {
void showZ() {
System.out.println("Class Z method");
// Mul ple Inheritance using Interface
interface P {
void showP();
interface Q {
void showQ();
class D implements P, Q {
public void showP() {
System.out.println("Interface P method");
public void showQ() {
System.out.println("Interface Q method");
}
JAVA LAB MANUAL
public class InheritanceDemo {
public sta c void main(String[] args) {
C obj1 = new C();
obj1.showA();
obj1.showB();
obj1.showC();
Z obj2 = new Z();
obj2.showX();
obj2.showZ();
D obj3 = new D();
obj3.showP();
obj3.showQ();
Result:
Successfully demonstrated mul level, hierarchical, and mul ple inheritance using `extends` and
`implements` keywords.
b) Write a java program to implement the concept of dynamic method dispatch.
Aim: To implement the concept of dynamic method dispatch.
Program:
JAVA LAB MANUAL
class Animal {
void sound() {
System.out.println("Animal is making a sound");
class Dog extends Animal {
void sound() {
System.out.println("Dog is barking");
class Cat extends Animal {
void sound() {
System.out.println("Cat is meowing");
public class DynamicDispatch {
public sta c void main(String[] args) {
Animal a = new Dog(); // Reference of Animal, object of Dog
a.sound(); // Calls Dog's sound()
a = new Cat(); // Reference of Animal, object of Cat
a.sound(); // Calls Cat's sound()
Result:
Successfully demonstrated dynamic method dispatch using overridden methods and run me
polymorphism.
JAVA LAB MANUAL
6)
a) Write a java program to implement stack concept using interface.
Experiment 6
a) Aim:
To implement the stack concept using an interface.
Program:
interface Stack {
void push(int item);
int pop();
class ArrayStack implements Stack {
private int[] stack;
private int top;
public ArrayStack(int size) {
stack = new int[size];
top = -1;
public void push(int item) {
if (top == stack.length - 1) {
System.out.println("Stack Overflow");
} else {
stack[++top] = item;
System.out.println("Pushed " + item);
}
JAVA LAB MANUAL
public int pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return -1;
} else {
return stack[top--];
public class StackDemo {
public sta c void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
stack.push(10);
stack.push(20);
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
Result: Successfully implemented a stack using an interface.
6)b) Write a java program to demonstrate the differences between access specifiers.
Aim: To demonstrate the differences between access specifiers.
Program:
class AccessSpecifierDemo {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30; // default
JAVA LAB MANUAL
private int privateVar = 40;
public void display() {
System.out.println("Public Var: " + publicVar);
System.out.println("Protected Var: " + protectedVar);
System.out.println("Default Var: " + defaultVar);
System.out.println("Private Var: " + privateVar);
public class AccessSpecifierTest {
public sta c void main(String[] args) {
AccessSpecifierDemo obj = new AccessSpecifierDemo();
obj.display();
System.out.println("Public Var: " + obj.publicVar);
System.out.println("Protected Var: " + obj.protectedVar);
System.out.println("Default Var: " + obj.defaultVar);
// obj.privateVar is not accessible here
Result: Successfully demonstrated access to variables with different access specifiers (`public`,
`protected`, `default`, and `private`).
7)a) Write a java program to create a user defined excep on that displays an error message when
user enters an integer value greater than n.
Experiment 7
a) Aim:
JAVA LAB MANUAL
To create a user-defined excep on that displays an error message when the user enters an integer
greater than `n`.
Program:
class MyExcep on extends Excep on {
MyExcep on(String message) {
super(message);
public class UserDefinedExcep on {
public sta c void main(String[] args) {
int n = 100;
int userInput = 150; // Example input greater than n
try {
if (userInput > n) {
throw new MyExcep on("Input is greater than " + n);
} catch (MyExcep on e) {
System.out.println(e.getMessage());
Result:
Successfully created a user-defined excep on that triggers when the input exceeds a specified limit.
7)b) Write a program to develop an applet that displays a simple message.
JAVA LAB MANUAL
b) Aim:
To develop an applet that displays a simple message.
Program:
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, this is a simple applet!", 20, 20);
HTML to run applet:
HTML
<applet code="SimpleApplet.class" width="300" height="200"></applet>
Result:
Successfully developed an applet that displays a simple message.
8)a) Write a java program to split a given text file into n parts. Name each part as the name of the
original file followed by .part where n is the sequence number of the part file.
Experiment 8
Aim:
JAVA LAB MANUAL
To write a Java program to split a given text file into `n` parts and name each part with the original
file followed by `.part`.
Program:
import java.io.*;
public class SplitFile {
public sta c void main(String[] args) throws IOExcep on {
FileInputStream fis = new FileInputStream("input.txt");
byte[] buffer = new byte[1024];
int n = 2; // Number of parts
int part = 1;
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
FileOutputStream fos = new FileOutputStream("input.part" + part++);
fos.write(buffer, 0, bytesRead);
fos.close();
fis.close();
System.out.println("File split successfully.");
Result: Successfully split the file into mul ple parts.
8)b) Write a java program to create a super class called Figure that receives the dimensions of two
dimensional objects. It also defines a method called area that computes the area of an object. The
program derives two subclasses from Figure.
b) Aim:
To create a superclass `Figure` that computes the area of two-dimensional objects and derive two
subclasses.
JAVA LAB MANUAL
Program:
class Figure {
double dim1, dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
double area() {
return 0;
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
double area() {
return dim1 * dim2;
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
JAVA LAB MANUAL
double area() {
return (dim1 * dim2) / 2;
public class FigureDemo {
public sta c void main(String[] args) {
Figure f1 = new Rectangle(10, 20);
Figure f2 = new Triangle(10, 20);
System.out.println("Area of Rectangle: " + f1.area());
System.out.println("Area of Triangle: " + f2.area());
Result:
Successfully demonstrated polymorphism by compu ng areas of different shapes.
9) a) Design a simple calculator which performs all arithme c opera ons.
Experiment 9: Simple Calculator and Event Handling
a) Simple Calculator
Aim:
To design a simple calculator in Java that performs all arithme c opera ons such as addi on,
subtrac on, mul plica on, and division.
Program:
import java.u l.Scanner;
JAVA LAB MANUAL
public class SimpleCalculator {
public sta c void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = sc.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
result = num1 / num2;
else {
System.out.println("Division by zero is not allowed.");
JAVA LAB MANUAL
return;
break;
default:
System.out.println("Invalid operator.");
return;
System.out.println("The result is: " + result);
Result:
The program successfully performs the required arithme c opera ons based on the user input.
9) b) Write a java program to handle keyboard and mouse events.
b) Keyboard and Mouse Events
Aim:
To write a Java program that handles keyboard and mouse events.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventHandlingExample extends JFrame implements KeyListener, MouseListener {
private JLabel label;
JAVA LAB MANUAL
public EventHandlingExample() {
label = new JLabel("Perform ac ons using keyboard or mouse");
label.setBounds(50, 50, 300, 30);
add(label);
addKeyListener(this);
addMouseListener(this);
setSize(400, 400);
setLayout(null);
setVisible(true);
setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
// KeyListener methods
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
public void keyReleased(KeyEvent e) {
label.setText("Key Released");
public void keyTyped(KeyEvent e) {
label.setText("Key Typed: " + e.getKeyChar());
// MouseListener methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + " Y: " + e.getY());
JAVA LAB MANUAL
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
public sta c void main(String[] args) {
new EventHandlingExample();
Result:
The program successfully detects and handles keyboard and mouse events, displaying corresponding
messages on the interface.
10) a) Understand the process of graphical user interface design and implementa on using swings.
Experiment 10: GUI Design with Swings and Integer Division
a) GUI Design using Swings
JAVA LAB MANUAL
Aim:
To understand the process of graphical user interface (GUI) design and implementa on using Swing
in Java.
Program:
import javax.swing.*;
public class SimpleSwingExample {
public sta c void main(String[] args) {
JFrame frame = new JFrame("Simple Swing Example");
JLabel label = new JLabel("Welcome to Java Swing!");
label.setBounds(50, 50, 200, 30);
frame.add(label);
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
Result:
The program successfully creates a simple graphical user interface using Swing that displays a
welcome message.
10) b) Write a Program that creates User Interface to perform Integer Divisons. The user enters two
numbers in text fields, Num1 and Num2.The division of Num1 and Num2 is displayed in the result
field when the divide bu on clicked. If Num1 or Num2 were not integer, the program would throw a
NumberFormatExcep on,If Num2 is Zero, and the program wouldthrow an Arithme cexcep on.
Display theExcep on in message box.
JAVA LAB MANUAL
b) Integer Division with Excep on Handling
Aim:
To write a Java program that creates a user interface to perform integer divisions, with excep on
handling for non-integer input and division by zero.
Program:
import javax.swing.*;
import java.awt.event.*;
public class IntegerDivisionGUI extends JFrame implements Ac onListener {
private JTextField num1Field, num2Field, resultField;
private JBu on divideBu on;
public IntegerDivisionGUI() {
setTitle("Integer Division");
JLabel num1Label = new JLabel("Num1:");
num1Label.setBounds(30, 30, 50, 30);
add(num1Label);
num1Field = new JTextField();
num1Field.setBounds(100, 30, 150, 30);
add(num1Field);
JLabel num2Label = new JLabel("Num2:");
num2Label.setBounds(30, 70, 50, 30);
add(num2Label);
num2Field = new JTextField();
num2Field.setBounds(100, 70, 150, 30);
add(num2Field);
JAVA LAB MANUAL
JLabel resultLabel = new JLabel("Result:");
resultLabel.setBounds(30, 110, 50, 30);
add(resultLabel);
resultField = new JTextField();
resultField.setBounds(100, 110, 150, 30);
resultField.setEditable(false);
add(resultField);
divideBu on = new JBu on("Divide");
divideBu on.setBounds(100, 150, 150, 30);
divideBu on.addAc onListener(this);
add(divideBu on);
setSize(300, 250);
setLayout(null);
setVisible(true);
setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
public void ac onPerformed(Ac onEvent e) {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
if (num2 == 0) {
throw new Arithme cExcep on("Division by zero");
int result = num1 / num2;
JAVA LAB MANUAL
resultField.setText(String.valueOf(result));
} catch (NumberFormatExcep on nfe) {
JOp onPane.showMessageDialog(this, "Please enter valid integers.",
"NumberFormatExcep on", JOp onPane.ERROR_MESSAGE);
} catch (Arithme cExcep on ae) {
JOp onPane.showMessageDialog(this, ae.getMessage(), "Arithme cExcep on",
JOp onPane.ERROR_MESSAGE);
public sta c void main(String[] args) {
new IntegerDivisionGUI();
Result:
The program creates a user-friendly interface that performs integer divisions and handles excep ons
for non-integer input and division by zero, displaying error messages in a message box.