Java Lab Manual
Java Lab Manual
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read
from command line arguments).
import java.util.Scanner;
class AddMatrix
{
public static void main(String args[])
{
int n,i,j;
Scanner in = new Scanner(System.in);
.IN
int mat1[][] = new int[n][n];
int mat2[][] = new int[n][n];
int res[][] = new int[n][n];
C
System.out.println("Enter the elements of matrix1");
for ( i= 0 ; i < n ; i++ )
N
{
for ( j= 0 ; j < n ;j++ )
SY
mat1[i][j] = in.nextInt();
}
System.out.println("Enter the elements of matrix2");
for ( i= 0 ; i < n ; i++ )
U
{
for ( j= 0 ; j < n ;j++ )
mat2[i][j] = in.nextInt();
VT
System.out.println("Sum of matrices:-");
for ( i= 0 ; i < n ; i++ )
{
for ( j= 0 ; j < n ;j++ )
System.out.print(res[i][j]+"\t");
System.out.println();
}
}
}
1|Page
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.
import java.util.Scanner;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
.IN
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
C
public int pop() {
if (top >= 0) {
N
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
SY
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
U
}
}
VT
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display Stack Contents");
System.out.println("0. Exit");
.IN
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
C
stack.push(valueToPush);
break;
N
case 2:
stack.pop();
SY
break;
case 3:
stack.peek();
break;
U
case 4:
stack.display();
break;
VT
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
}
}
3|Page
Output: Stack Menu:
Stack Menu: 1. Push
1. Push 2. Pop
2. Pop 3. Peek
3. Peek 4. Display Stack Contents
4. Display Stack Contents 0. Exit
0. Exit Enter your choice: 2
Enter your choice: 1 Popped: 20
Enter the value to push: 10
Pushed: 10 Stack Menu:
1. Push
Stack Menu: 2. Pop
1. Push 3. Peek
2. Pop 4. Display Stack Contents
3. Peek 0. Exit
4. Display Stack Contents Enter your choice: 4
0. Exit Stack Contents: 10
Enter your choice: 1
Enter the value to push: 20 Stack Menu:
.IN
Pushed: 20 1. Push
2. Pop
Stack Menu: 3. Peek
1. Push 4. Display Stack Contents
C
2. Pop 0. Exit
3. Peek Enter your choice: 3
N
4. Display Stack Contents Stack Contents: 10
0. Exit Peeked: 20
SY
1. Push 3. Peek
2. Pop 4. Display Stack Contents
VT
3. Peek 0. Exit
4. Display Stack Contents Enter your choice: 0
0. Exit Exiting the program. Goodbye!
Enter your choice: 3
Peeked: 20
4|Page
3. A class called Employee, which models an employee with an ID, name and salary, is designed as
shown in the following class diagram. The method raiseSalary (percent) increases the salary by the
given percentage. Develop the Employee class and suitable main method for demonstration.
.IN
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}
C
public String toString() {
N
return "Employee ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
SY
System.out.println(employee);
5|Page
4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0). ● A
overloaded constructor that constructs a point with the given x and y coordinates. ● A method
setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another point
at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin
(0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to
test all the methods defined in the class.
class MyPoint {
private int x;
private int y;
.IN
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
C
}
N
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
SY
this.y = y;
}
this.y = y;
}
.IN
point1.getXY()[1]);
}
}
Output:
U
7|Page
5. Develop a JAVA program to create a class named shape. Create three sub classes namely: circle,
triangle and square, each class has two member functions named draw() and erase(). Demonstrate
polymorphism concepts by developing suitable methods, defining member data and main
program.
class Shape {
public void draw() {
System.out.println("Drawing a shape...");
}
// Circle subclass
class Circle extends Shape {
public void draw() {
System.out.println("Drawing a circle...");
}
.IN
public void erase() {
System.out.println("Erasing a circle...");
}
C
}
N
// Triangle subclass
class Triangle extends Shape {
SY
// Square subclass
class Square extends Shape {
public void draw() {
System.out.println("Drawing a square...");
}
6. Develop a JAVA program to create an abstract class Shape with abstract methods calculateArea()
and calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and perimeter of each shape.
.IN
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
U
@Override
double calculatePerimeter() {
VT
9|Page
@Override
double calculatePerimeter() {
return side1 + side2 + side3; Output:
} Circle Area: 78.53981633974483
} Circle Perimeter: 31.41592653589793
Triangle Area: 6.0
public class ShapeDemo { Triangle Perimeter: 12.0
public static void main(String[] args) {
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
.IN
7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements
the Resizable interface and implements the resize methods.
C
interface Resizable {
N
void resizeWidth(int width);
void resizeHeight(int height);
SY
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
10 | P a g e
// Additional methods for Rectangle class
public int getWidth() {
return width;
}
.IN
Original Rectangle Info:
// Displaying the original information Rectangle: Width = 15, Height = 10
System.out.println("Original Rectangle Info:"); Resized width to: 20
rectangle.displayInfo(); Resized height to: 10
C
// Resizing the rectangle Updated Rectangle Info:
rectangle.resizeWidth(20); Rectangle: Width = 20, Height = 10
N
rectangle.resizeHeight(10);
SY
}
VT
8. Develop a JAVA program to create an outer class with a function display. Create another class inside
the outer class named inner with a function called display and call the two functions in the main class.
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
9. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
.IN
}
}
}
return (double) numerator / denominator;
}
Output:
U
public static void main(String[] args) { Exception caught: Cannot divide by zero!
int numerator = 10; Finally block executed
VT
int denominator = 0;
try {
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
10. Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
package mypack;
.IN
int result = MyPackageClass.addNumbers(5, 4);
System.out.println("Result of adding numbers: " + result);
}
}
C
Organize your directory structure as follows:
N
project-directory/
SY
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
U
VT
Output:
Hello from MyPackageClass in mypack package!
Result of adding numbers: 9
11. Write a program to illustrate creation of threads using runnable class. (start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).
@Override
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
13 | P a g e
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
thread4.start();
thread5.start();
VT
14 | P a g e
Output: Note:
Thread ID: 24 is running. In this program, we define a MyRunnable class that implements
Thread ID: 21 is running. the Runnable interface. The run method contains a loop where
Thread ID: 20 is running. the thread sleeps for 500 milliseconds, printing its ID during each
Thread ID: 23 is running. iteration. We also handle potential interruptions caused by thread
Thread ID: 22 is running. operations.
12. Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It can be
observed that both main thread and created child thread are executed concurrently.
.IN
class MyThread extends Thread {
// Constructor calling base class constructor using super
public MyThread(String name) {
super(name);
C
start(); // Start the thread in the constructor
}
N
// The run method that will be executed when the thread starts
SY
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
U
try {
Thread.sleep(500); // Sleep for 500 milliseconds
VT
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}
// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
15 | P a g e
}
}
}
Output: Note:
main Thread Count: 1 In this program:
Child Thread Count: 1 • The MyThread class extends Thread.
Child Thread Count: 2
• The constructor of MyThread calls the base class constructor using
main Thread Count: 2
super(name) to set the thread’s name and starts the thread.
Child Thread Count: 3
• The run method is overridden and contains a loop to print counts. The
main Thread Count: 3
thread sleeps for 500 milliseconds in each iteration.
Child Thread Count: 4
main Thread Count: 4 • In the main method, an instance of MyThread is created, which starts
Child Thread Count: 5 the child thread concurrently.
main Thread Count: 5 • The main thread also prints counts and sleeps for 500 milliseconds in
each iteration.
When you run this program, you’ll observe that both the main thread and
the child thread are executed concurrently, and their outputs may be
interleaved.
.IN
C
N
SY
U
VT
16 | P a g e