Java Lab Programs
Java Lab Programs
Java Lab Programs
Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
public class MatrixAddition {
public static void main(String[] args) {
// Check if the number of command line arguments is correct
if (args.length != 1) {
System.out.println("Usage: java MatrixAddition <order_N>");
return;
}
// Parse the command line argument to get the order N
int N = Integer.parseInt(args[0]);
// Check if N is a positive integer
if (N <= 0) {
System.out.println("Please provide a valid positive integer for the order N.");
return;
}
// Create two matrices of order N
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
// Fill the matrices with some sample values (you can modify this as needed)
fillMatrix(matrix1, 1);
fillMatrix(matrix2, 2);
// Print the matrices
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("\nMatrix 2:");
printMatrix(matrix2);
// Add the matrices
int[][] resultMatrix = addMatrices(matrix1, matrix2);
// Print the result matrix
System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
printMatrix(resultMatrix);
}
// Helper method to fill a matrix with sequential values
private static void fillMatrix(int[][] matrix, int startValue) {
int value = startValue;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = value++;
}
}
}
// Helper method to add two matrices
private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int N = matrix1.length;
int[][] resultMatrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return resultMatrix;
}
// Helper method to print a matrix
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + "\t");
}
System.out.println();
}
}
}
Output
$ java MatrixAddition 3
Matrix 1:
1 2 3
4 5 6
7 8 9
Matrix 2:
2 3 4
5 6 7
8 9 10
Resultant Matrix (Matrix1 + Matrix2):
3 5 7
9 11 13
15 17 19
Program 02 : Stack Operations
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 class Stack {
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
public void push(int value) {
if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}
public void display() {
if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == MAX_SIZE - 1;
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
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("5. Check if the stack is empty");
System.out.println("6. Check if the stack is full");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 6:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();
}
}
Output
$ java Stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 4
Stack is empty.
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 5
Is the stack empty? true
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 6
Is the stack full? false
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 1
Enter the value to push: 10
Pushed: 10
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 1
Enter the value to push: 20
Pushed: 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 4
Stack Contents: 10 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 3
Peeked: 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 1
Enter the value to push: 30
Pushed: 30
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 4
Stack Contents: 10 20 30
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 2
Popped: 30
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 3
Peeked: 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 4
Stack Contents: 10 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 0
Exiting the program. Goodbye!
Program 03 : Employee Class
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.
public class Employee {
private int id;
private String name;
private double salary;
Output
$ java Employee
Initial Employee Details:
Employee ID: 1, Name: John Doe, Salary: $50000.0
John Doe's salary raised by 10.0%. New salary: $55000.0
TestMyPoint.java
public class TestMyPoint {
public static void main(String[] args) {
// Creating MyPoint objects using different constructors
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Testing setXY and getXY methods
point1.setXY(1, 2);
System.out.println("Point1 coordinates after setXY: " + point1.getXY()[0] + ", " +
point1.getXY()[1]);
// Testing toString method
System.out.println("Point2 coordinates: " + point2.toString());
// Testing distance methods
System.out.println("Distance from Point1 to Point2: " + point1.distance(point2));
System.out.println("Distance from Point2 to Origin: " + point2.distance());
}
}
Output
$ java TestMyPoint
Point1 coordinates after setXY: 1, 2
Point2 coordinates: (3, 4)
Distance from Point1 to Point2: 2.8284271247461903
Distance from Point2 to Origin: 5.0
Output
$ java ShapeDemo
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
Drawing a triangle with base 4.0 and height 6.0
Erasing a triangle with base 4.0 and height 6.0
Drawing a square with side length 3.0
Erasing a square with side length 3.0
Output
$ java ShapeDemo
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Triangle Area: 6.0
Triangle Perimeter: 12.0
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
Output
$ java OuterInnerDemo
Outer class display method
Inner class display method
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");
}
}
}
Output
$ java CustomExceptionDemo
Exception caught: Cannot divide by zero!
Finally block executed
Program 10 : Packages
Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Package mypack
Now, let’s create the main program in a different file outside the mypack folder:
PackageDemo class using mypack Package
Output:
$ java PackageDemo
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
Program 11 : Runnable Interface
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).
class MyRunnable implements Runnable {
private volatile boolean running = true;
@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is
running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
public void stopThread() {
running = false;
}
}
$ java RunnableThreadExample
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.
// The run method that will be executed when the thread starts
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} 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.");
}
}
}
}
Output
$ java ThreadConcurrentExample
main Thread Count: 1
Child Thread Count: 1
main Thread Count: 2
Child Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5