Lab Manual - Java
Lab Manual - Java
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
Java Code:
if (args.length != 1)
{
System.out.println("Usage: java MatrixAddition <order_N>");
return;
}
int N = Integer.parseInt(args[0]);
if (N <= 0)
{
System.out.println("Please provide a valid positive integer for the order N.");
return;
}
// Fill the matrices with some sample values (you can modify this as needed
)
fillMatrix(matrix1, 1);
fillMatrix(matrix2, 2);
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("\nMatrix 2:");
printMatrix(matrix2);
}
}
}
In this example, the matrices are filled with sequential values for simplicity, but you can modify
the fillMatrix method to fill the matrices with any values you prefer.
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
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
Java Code:
import java.util.Scanner;
public Stack()
{
stackArray = new int[MAX_SIZE];
top = -1;
}
switch (choice)
{
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
lOMoAR cPSD| 41782632
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
lOMoAR cPSD| 41782632
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
lOMoAR cPSD| 41782632
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
lOMoAR cPSD| 41782632
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!
lOMoAR cPSD| 41782632
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.
Java Code:
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
4.A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
Java Code:
MyPoint.java
public class MyPoint {
private int x;
private int y;
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
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
lOMoAR cPSD| 41782632
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.
Java Code:
class Shape {
protected String name;
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}
@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
lOMoAR cPSD| 41782632
@Override
public void erase() {
System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}
@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}
@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}
Output:
$ java ShapeDemo
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
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.
Java Code:
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
lOMoAR cPSD| 41782632
Output:
$ java ShapeDemo
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Java Code:
// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
Output:
$ java ResizeDemo
Original Rectangle Info:
Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 8
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.
Java Code:
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
Output:
$ java OuterInnerDemo
Outer class display method
Inner class display method
lOMoAR cPSD| 41782632
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
Java Code:
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");
}
}
}
In this program:
The DivisionByZeroException class is a custom exception that extends the Exception class.
The divide method performs division and throws the custom exception if the denominator is zero.
In the main method, we attempt to divide and catch the custom exception if it occurs. The finally
block is used for code that must be executed, whether an exception is thrown or not.
When you run this program with a denominator of 0, it will throw the DivisionByZeroException,
catch it, print the error message, and then execute the finally block.
Output:
$ java CustomExceptionDemo
Exception caught: Cannot divide by zero!
Finally block executed
lOMoAR cPSD| 41782632
Program 10 : Packages
10. Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Java Code:
Package mypack
// Inside a folder named 'mypack'
package mypack;
project-directory/
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
Compile the files:
javac mypack/MyPackageClass.java
javac PackageDemo.java
Output:
$ java PackageDemo
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
lOMoAR cPSD| 41782632
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).
Java Code:
@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.");
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Output:
$ 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.
lOMoAR cPSD| 41782632
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.
Java Code:
// 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.");
}
}
}
}
public class ThreadConcurrentExample {
public static void main(String[] args) {
// Create an instance of MyThread
MyThread myThread = new MyThread("Child Thread");
// 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.");
}
}
}
}
In this program:
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.
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