JAVA LAB Manual 3 RD Sem Vtu
JAVA LAB Manual 3 RD Sem Vtu
181/1, 182/1, Sonnenahalli, Hoodi, K.R.Puram, Whitefield, Bangalore, Karnataka - 560 048
Phone No: 080 – 42229748 Email: [email protected] Website:
www.gopalancolleges.com/gcem
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) {
return;
int N = Integer.parseInt(args[0]);
if (N <= 0) {
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);
printMatrix(resultMatrix);
matrix[i][j] = value++;
}
// Helper method to add two matrices
int N = matrix1.length;
return resultMatrix;
System.out.print(value + "\t");
System.out.println();
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
3 5 7
9 11 13
15 17 19
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() {
top = -1;
stackArray[++top] = value;
if (top >= 0) {
return poppedValue;
} else {
if (top >= 0) {
return stackArray[top];
} else {
if (top >= 0) {
System.out.println();
} else {
System.out.println("Stack is empty.");
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("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
break;
case 6:
break;
case 0:
break;
default:
Output
$ java Stack
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack is empty.
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Pushed: 10
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Contents: 10 20
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Peeked: 20
Stack Menu:
1. Push
2. Pop
3. Peek
Pushed: 30
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Contents: 10 20 30
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Popped: 30
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Peeked: 20
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
Stack Contents: 10 20
Stack Menu:
1. Push
2. Pop
3. Peek
0. Exit
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
this.id = id;
this.name = name;
this.salary = salary;
if (percent > 0) {
salary += raiseAmount;
System.out.println(name + "'s salary raised by " + percent + "%. New salary: $" + salary);
} else {
return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}
public static void main(String[] args) {
System.out.println(employee);
employee.raiseSalary(10);
System.out.println(employee);
In this example, the Employee class has a constructor to initialize the employee’s ID, name, and
salary. The raiseSalary method takes a percentage as a parameter and raises the salary accordingly.
The toString method is overridden to provide a meaningful string representation of
the Employee object. The main method demonstrates the usage of the Employee class by creating
an instance, displaying its details, raising the salary, and then displaying the updated details.
Output
$ java Employee
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
● A overloaded constructor that constructs a point with the given x and y coordinates.
● 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.
MyPoint.java
private int x;
private int y;
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
// Overloaded constructor
this.x = x;
this.y = y;
this.x = x;
this.y = y;
TestMyPoint.java
public class TestMyPoint {
point1.setXY(1, 2);
This TestMyPoint program creates two MyPoint objects, sets and retrieves coordinates, and tests
the various distance calculation methods. Feel free to modify and expand this code as needed.
Output
$ java TestMyPoint
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 {
this.name = name;
super(name);
this.radius = radius;
@Override
@Override
public void erase() {
super(name);
this.base = base;
this.height = height;
@Override
System.out.println("Drawing a triangle with base " + base + " and height " + height);
@Override
System.out.println("Erasing a triangle with base " + base + " and height " + height);
super(name);
this.side = side;
@Override
@Override
shape.draw();
shape.erase();
System.out.println();
In this program, the Shape class is the superclass, and Circle, Triangle, and Square are its subclasses.
The draw() and erase() methods are overridden in each subclass. The main method creates an array
of Shape objects and initializes it with instances of the different subclasses. When iterating through
the array and calling the draw() and erase() methods, polymorphism allows the appropriate
overridden methods in each subclass to be executed.
Output
$ java ShapeDemo
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
this.radius = radius;
@Override
double calculateArea() {
@Override
double calculatePerimeter() {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
@Override
double calculateArea() {
@Override
double calculatePerimeter() {
}
public class ShapeDemo {
Output
$ java ShapeDemo
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.
Java Code
// Resizable interface
interface Resizable {
void resizeWidth(int width);
this.width = width;
this.height = height;
@Override
this.width = width;
@Override
this.height = height;
return width;
}
public int getHeight() {
return height;
rectangle.displayInfo();
rectangle.resizeWidth(15);
rectangle.resizeHeight(8);
rectangle.displayInfo();
In this program, the Resizable interface declares the methods resizeWidth and resizeHeight.
The Rectangle class implements this interface and provides the specific implementation for resizing
the width and height. The main method in the ResizeDemo class creates a Rectangle object, displays
its original information, resizes it, and then displays the updated information.
Output
$ java ResizeDemo
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() {
class Inner {
void display() {
outer.display();
inner.display();
In this program, the Outer class has a method named display, and it also contains an inner class
named Inner with its own display method. In the main method of the OuterInnerDemo class, an
instance of the outer class (Outer) is created, and its display method is called. Then, an instance of
the inner class (Inner) is created using the outer class instance, and its display method is called. This
demonstrates the concept of nesting classes in Java.
Output
$ java OuterInnerDemo
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
Java Code
super(message);
if (denominator == 0) {
int denominator = 0;
try {
} catch (DivisionByZeroException e) {
} finally {
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!
Program 10 : Packages
Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Java Code
Package mypack
package mypack;
return a + b;
Now, let’s create the main program in a different file outside the mypack folder:
import mypack.MyPackageClass;
//import mypack.*;
myPackageObject.displayMessage();
To compile and run this program, you need to follow these steps:
project-directory/
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
javac mypack/MyPackageClass.java
javac PackageDemo.java
Output
$ java PackageDemo
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 {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
running = false;
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
In this program, we define a MyRunnable class that implements the Runnable interface.
The run method contains a loop where the thread sleeps for 500 milliseconds, printing its ID during
each iteration. We also handle potential interruptions caused by thread operations.
In the RunnableThreadExample class, we create five instances of MyRunnable, each associated with
a separate thread. The start method is called on each thread, initiating their concurrent execution.
After a brief period of allowing the threads to run, we gracefully stop each thread using
the stopThread method.
Output
$ java RunnableThreadExample
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
super(name);
// The run method that will be executed when the thread starts
@Override
try {
} catch (InterruptedException e) {
}
public class ThreadConcurrentExample {
// Main thread
try {
} catch (InterruptedException e) {
In this program:
● The constructor of MyThread calls the base class constructor using super(name) to set the
thread’s name and starts the thread.
● The run method is overridden and contains a loop to print counts. The thread sleeps for 500
milliseconds in each iteration.
● In the main method, an instance of MyThread is created, which starts the child thread
concurrently.
● 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.
Output
$ java ThreadConcurrentExample