2022 Java Lab Manual
2022 Java Lab Manual
III SEMESTER
ObjectOrientedProgrammingwithJAVA
(BCS306A)
1
2
VISION
MISSION
III SEMESTER
ObjectOrientedProgrammingwithJAVA
(BCS306A)
2
3
ObjectOrientedProgrammingwithJAVA
(BCS306A)
PREPARED BY
THRIPURAMBHA M P
(TUTOR)
DEPT OF CSE
RRCE,BANGALORE
3
4
int N = Integer.parseInt(args[0]);
if (N <= 0) {
System.out.println("Order N should be a positive integer.");
return;
}
// Populate the matrices with values (You can modify this part)
// For simplicity, we'll use a counter to fill the matrices.
int counter = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrixA[i][j] = counter;
matrixB[i][j] = counter * 2;
counter++;
}
}
4
5
System.out.println("Matrix B:");
printMatrix(matrixB);
In this program, we first validate the command-line argument, initialize two matrices with
sample values, perform matrix addition, and then display the original matrices and the result
matrix. You can modify the code to accept user input or generate matrices differently if needed.
5
6
Java program that defines a simple stack class to hold a maximum of 10 integers and provides
methods for stack operations. We will also develop a main method to illustrate stack operations:
6
7
stack.push(5);
stack.push(10);
stack.push(15);
stack.display();
7
8
3. A class called Employee, which models an employee with an ID, name and
salary, is designed as shown inthe following class diagram. The method
raiseSalary (percent) increases the salary by the givenpercentage. Develop the
Employee class and suitable main method for demonstration.
Based on the class diagram you provided, here's a simple implementation of the Employee class
in Java:
8
9
9
1
// Default constructor
public MyPoint() {
x = 0;
y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
1
0
1
this.y = y;
}
// Method to return a string description of the instance in the format "(x, y)"
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
// Method to calculate distance from this point to another point at given (x, y) coordinates
public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
// Overloaded method to calculate distance from this point to another MyPoint instance
public double distance(MyPoint another) {
return distance(another.x, another.y);
}
// Overloaded method to calculate distance from this point to the origin (0, 0)
public double distance() {
return distance(0, 0);
}
}
Now, let's create a TestMyPoint class to test all the methods defined in the MyPoint class:
1
1
1
This TestMyPoint class creates instances of MyPoint and tests each of the defined methods.
1
2
1
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.
Sure, let's create the Shape class and its three subclasses Circle, Triangle, and
Square to demonstrate polymorphism:
// Shape class
class Shape {
public void draw() {
System.out.println("Drawing a generic shape");
}
@Override
public void erase() {
System.out.println("Erasing the circle");
}
}
@Override
public void erase() {
System.out.println("Erasing the triangle");
}
}
1
3
1
@Override
public void erase() {
System.out.println("Erasing the square");
}
}
// Main program
public class TestShapes {
public static void main(String[] args) {
// Creating objects of different shapes
Shape genericShape = new Shape();
Circle circle = new Circle();
Triangle triangle = new Triangle();
Square square = new Square();
// Demonstrating polymorphism
drawAndErase(genericShape);
drawAndErase(circle);
drawAndErase(triangle);
drawAndErase(square);
}
// Polymorphic method
public static void drawAndErase(Shape shape) {
shape.draw();
shape.erase();
System.out.println(); // Adding a newline for better readability
}
}
In this example, the Shape class is the base class, and Circle, Triangle, and Square are its
subclasses. Each subclass overrides the draw() and erase() methods to provide specific
implementations for each shape. The TestShapes class demonstrates polymorphism by creating
objects of different shapes and invoking the drawAndErase method with objects of the Shape
type. The actual method called depends on the runtime type of the object, showcasing
polymorphic behavior.
1
4
1
6. Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() andcalculatePerimeter(). Create subclasses Circle and Triangle that extend
the Shape class and implementthe respective methods to calculate the area and perimeter
of each shape.
this.radius = radius;
@Override
@Override
1
5
1
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
@Override
@Override
1
6
1
// Main program
In this program, the Shape class is an abstract class with abstract methods calculateArea() and
calculatePerimeter(). The Circle and Triangle classes extend the Shape class and provide
concrete implementations for these methods to calculate the area and perimeter of a circle and a
triangle, respectively. The TestShapes class demonstrates creating objects of these shapes and
calculating/displaying their area and perimeter.
1
7
1
Here's a Java program that creates an interface Resizable with methods resizeWidth(int width)
and resizeHeight(int height), and a class Rectangle that implements the Resizable interface and
provides implementations for the resize methods:
// Resizable interface
interface Resizable {
this.width = width;
this.height = height;
@Override
this.width = width;
1
8
1
@Override
this.height = height;
// Main program
System.out.println("Initial Rectangle:");
rectangle.display();
1
9
2
rectangle.resizeWidth(15);
rectangle.resizeHeight(25);
System.out.println("Final Rectangle:");
rectangle.display();
In this program, the Resizable interface declares methods resizeWidth(int width) and
resizeHeight(int height). The Rectangle class implements the Resizable interface and provides
concrete implementations for these methods. The TestResizable class demonstrates creating an
object of the Rectangle class, displaying its initial state, resizing its width and height, and then
displaying the final state.
2
0
2
// Outer class
class Outer {
void display() {
// Inner class
class Inner {
void display() {
// Main class
2
1
2
outerObj.display();
innerObj.display();
In this example, the Outer class contains a method named display. Inside the Outer class, there is
an Inner class with its own display method. In the Main class, an instance of the outer class is
created, and its display method is called. Then, an instance of the inner class is created using the
outer class instance (outerObj.new Inner()), and its display method is called.
This demonstrates the concept of an outer class containing an inner class, each with its own
display method, and how to call these methods from the main class.
2
2
2
Here's an example of a Java program that raises a custom exception (DivisionByZeroException) for
division by zero using try, catch, throw, and finally:
// Main class
public class Main {
public static void main(String[] args) {
try {
// Perform division
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (DivisionByZeroException e) {
// Catch the custom exception and print the error message
System.out.println("Exception caught: " + e.getMessage());
} finally {
// This block will be executed no matter what, whether an exception occurs or not
System.out.println("Finally block executed");
}
}
In this example:
2
3
2
The divide method attempts to perform division but catches the built-in
ArithmeticException (thrown when dividing by zero) and rethrows it as a
DivisionByZeroException with a custom error message.
In the main method, we call the divide method, and if a DivisionByZeroException is
thrown, we catch it and print the custom error message. The finally block is executed
regardless of whether an exception occurs or not.
When you run this program and attempt to divide by zero, it will catch the custom exception and
print the error message, and the finally block will be executed.
10. Develop a JAVA program to create a package named mypack and import
& implement it in a suitableclass.
2
4
2
create a package named mypack and import and implement it in a suitable class.
Let's create a simple package with a class in it:
Create a directory named mypack.
Inside the mypack directory, create a file named MyPackageClass.java with the following
content:
// File: mypack/MyPackageClass.java
package mypack;
2
5
2
// Runnable class
class MyRunnable implements Runnable {
@Override
public void run() {
try {
// Print the thread name and ID
System.out.println("Thread " + Thread.currentThread().getName() + " (ID: " +
Thread.currentThread().getId() + ") is running.");
// Main class
public class ThreadExample {
public static void main(String[] args) {
// Create two instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
// Create two threads and pass the instances of MyRunnable to their constructors
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
In this example:
2
6
2
The MyRunnable class implements the Runnable interface and overrides the run method.
Inside the run method, the thread's name and ID are printed, followed by a sleep
statement that suspends the thread for 500 milliseconds.
The ThreadExample class creates two instances of MyRunnable, creates two threads, and
starts them using the start method.
When you run this program, you may observe interleaved output from the two threads as they
run concurrently. The sleep statement inside the run method introduces a delay, allowing you to
see how the threads can be suspended for a short period.
2
7
2
method of the class starts after this. It can be observed thatboth main thread
and created child thread are executed concurrently.
class MyThread with a constructor, calls the base class constructor using super, and starts the
thread. The run method of the class then executes, demonstrating concurrent execution of the
main thread and the created child thread.
// MyThread class
class MyThread extends Thread {
// Constructor of MyThread class
public MyThread(String threadName) {
// Call the base class (Thread) constructor using super
super(threadName);
}
// Main class
public class ThreadExample {
public static void main(String[] args) {
// Create an instance of MyThread with the name "ChildThread"
MyThread myThread = new MyThread("ChildThread");
2
8
2
2
9