3rd Sem, B.
E [CSE] : OOP with JAVA Lab[ BCS306A]
OBJECT ORIENTED PROGRAMMING WITH JAVA 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).
package sample;
import java.util.Scanner;
class Main
{
public static void main(String a[])
{
int i,j;
Scanner in = new Scanner(System.in);
int N=Integer.parseInt(a[0]) ;
System.out.println("The order of matrices (N): "+N);
int mat1[][] = new int[N][N];
int mat2[][] = new int[N][N];
int add[][] = new int[N][N];
System.out.println("Enter the elements of matrix1");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
mat1[i][j] = in.nextInt();
System.out.println();
}
System.out.println("Enter the elements of matrix2");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
mat2[i][j] = in.nextInt();
System.out.println();
}
for ( i= 0 ; i < N ; i++ )
Dept. of CSE, VVIET, Mysuru Page 1
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
for ( j= 0 ; j < N ;j++ )
add[i][j] = mat1[i][j] + mat2[i][j] ;
System.out.println("Sum of two matrices:-");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
System.out.print(add[i][j]+"\t");
System.out.println();
}
}
}
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
public class Stack {
private int maxSize;
private int top;
private int[] stackArray;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack is full. Cannot push " + value);
}
}
public int pop() {
if (!isEmpty()) {
int value = stackArray[top--];
System.out.println("Popped: " + value);
Dept. of CSE, VVIET, Mysuru Page 2
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
return value;
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // You can choose a different value to represent an empty stack
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public static void main(String[] args) {
Stack stack = new Stack(10);
System.out.println("Is the stack empty? " + stack.isEmpty());
System.out.println("Is the stack full? " + stack.isFull());
// Pushing elements onto the stack
for (int i = 1; i <= 10; i++) {
stack.push(i * 10);
}
System.out.println("Is the stack empty? " + stack.isEmpty());
System.out.println("Is the stack full? " + stack.isFull());
// Popping elements from the stack
for (int i = 1; i <= 5; i++) {
stack.pop();
}
}
}
OUTPUT: Is the stack empty? true
Is the stack full? false
Pushed: 10
Pushed: 20
Dept. of CSE, VVIET, Mysuru Page 3
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
Pushed: 30
Pushed: 40
Pushed: 50
Pushed: 60
Pushed: 70
Pushed: 80
Pushed: 90
Pushed: 100
Is the stack empty? false
Is the stack full? true
Popped: 100
Popped: 90
Popped: 80
Popped: 70
Popped: 60
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.
public class Employee {
// Instance variables
private int id;
private String name;
private double salary;
// Constructor
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// Getter methods
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
Dept. of CSE, VVIET, Mysuru Page 4
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
// Method to raise salary by a given percentage
public void raiseSalary(double percent) {
if (percent > 0) {
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
System.out.println("Salary raised by " + percent + "%. New salary: $" + salary);
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}
public static void main(String[] args) {
// Creating an Employee object
Employee employee = new Employee(101, "John Doe", 50000.0);
// Displaying initial information
System.out.println("Employee Details:");
System.out.println("ID: " + employee.getId());
System.out.println("Name: " + employee.getName());
System.out.println("Salary: $" + employee.getSalary());
// Raising the salary by 10%
employee.raiseSalary(10);
// Displaying updated information
System.out.println("\nUpdated Employee Details:");
System.out.println("ID: " + employee.getId());
System.out.println("Name: " + employee.getName());
System.out.println("Salary: $" + employee.getSalary());
}
}
OUTPUT: Employee Details:
ID: 101
Name: John Doe
Salary: $50000.0
Salary raised by 10.0%. New salary: $55000.0
Updated Employee Details:
Dept. of CSE, VVIET, Mysuru Page 5
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
ID: 101
Name: John Doe
Salary: $55000.0
4. 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 {
// Member functions
public void draw() {
System.out.println("Drawing a shape");
}
public void erase() {
System.out.println("Erasing a shape");
}
}
// Circle class
class Circle extends Shape {
// Override draw method
@Override
public void draw() {
System.out.println("Drawing a circle");
}
// Override erase method
@Override
public void erase() {
System.out.println("Erasing a circle");
}
}
// Triangle class
class Triangle extends Shape {
// Override draw method
@Override
public void draw() {
Dept. of CSE, VVIET, Mysuru Page 6
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
System.out.println("Drawing a triangle");
}
// Override erase method
@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}
// Square class
class Square extends Shape {
// Override draw method
@Override
public void draw() {
System.out.println("Drawing a square");
}
// Override erase method
@Override
public void erase() {
System.out.println("Erasing a square");
}
}
// Main program
public class lab {
public static void main(String[] args) {
// Creating objects of different shapes
Shape circle = new Circle();
Shape triangle = new Triangle();
Shape square = new Square();
// Demonstrating polymorphism
// Calls to overridden draw and erase methods
circle.draw();
circle.erase();
Dept. of CSE, VVIET, Mysuru Page 7
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
triangle.draw();
triangle.erase();
square.draw();
square.erase();
}
}
OUTPUT: Erasing a circle
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square
5. 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
// Implement the Resizable interface in the Rectangle class
class Rectangle implements Resizable {
private int width;
private int height;
// Constructor for Rectangle
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// Getter methods for width and height
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
// Implementation of resizeWidth method from Resizable interface
@Override
public void resizeWidth(int width) {
Dept. of CSE, VVIET, Mysuru Page 8
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
this.width = width;
}
// Implementation of resizeHeight method from Resizable interface
@Override
public void resizeHeight(int height) {
this.height = height;
}
}
public class Main {
public static void main(String[] args) {
// Create an object of Rectangle
Rectangle rectangle = new Rectangle(10, 5);
// Display the initial width and height
System.out.println("Initial Width: " + rectangle.getWidth());
System.out.println("Initial Height: " + rectangle.getHeight());
// Resize the rectangle
rectangle.resizeWidth(15);
rectangle.resizeHeight(8);
// Display the resized width and height
System.out.println("Resized Width: " + rectangle.getWidth());
System.out.println("Resized Height: " + rectangle.getHeight());
}
}
OUTPUT:
Initial Width: 10
Initial Height: 5
Resized Width: 15
Resized Height: 8
6. 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.
Dept. of CSE, VVIET, Mysuru Page 9
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
// Outer class
class Outer {
void display() {
System.out.println("Outer class display");
}
// Inner class
class Inner {
void display() {
System.out.println("Inner class display");
}
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an instance of the outer class
Outer outerObj = new Outer();
// Call the display method of the outer class
outerObj.display();
// Create an instance of the inner class using the outer class instance
Outer.Inner innerObj = outerObj.new Inner();
// Call the display method of the inner class
innerObj.display();
}
}
OUTPUT: Outer class display
Inner class display
7. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
// Custom exception class
class DivisionByZeroException extends Exception {
Dept. of CSE, VVIET, Mysuru Page 10
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
public DivisionByZeroException(String message) {
super(message);
}
}
// Main class
public class Main {
public static void main(String[] args) {
try {
// Perform division operation
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (DivisionByZeroException e) {
// Catch the custom exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
// Finally block, can be used for cleanup or other tasks
System.out.println("Finally block executed.");
}
}
// Method that may throw the custom exception
static int divide(int numerator, int denominator) throws DivisionByZeroException {
try {
// Check for division by zero
if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
// Perform the division
return numerator / denominator;
} catch (ArithmeticException e) {
// Catch any arithmetic exceptions
throw new DivisionByZeroException("Arithmetic exception: " + e.getMessage());
}
}
}
OUTPUT: Exception caught: Division by zero is not allowed.
Finally block executed.
8. Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Dept. of CSE, VVIET, Mysuru Page 11
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
STEP1 : CREATE A PACKAGE NAME Mypackage
STEP 2: CREATE A CLASS MyClass within that package Mypackage.(type the below code)
// File: Mypackage/MyClass.java
package Mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in mypack!");
}
}
STEP 3: WITHIN ANOTHER PACKAGE CREATE A CLASS NAME MainClass(type the below code)
//File: MainClass.java
import Mypackage.MyClass;
public class MainClass {
public static void main(String[] args) {
// Create an instance of MyClass from the mypack package
MyClass myObject = new MyClass();
// Call the displayMessage method from MyClass
myObject.displayMessage();
}
}
STEP 4: RUN THE MyClass.java and MainClass. Java
OUTPUT: Hello from MyClass in mypack!
9. 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 {
@Override
public void run() {
try {
// Displaying the current thread's name
System.out.println("Thread: " + Thread.currentThread().getName() + " is running.");
// Simulate some work using sleep
Thread.sleep(500);
// Displaying a message after sleep
System.out.println("Thread: " + Thread.currentThread().getName() + " has completed.");
} catch (InterruptedException e) {
e.printStackTrace();
Dept. of CSE, VVIET, Mysuru Page 12
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
}
}
}
public class ThreadExample {
public static void main(String[] args) {
// Create instances of the MyRunnable class
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
// Create threads using the MyRunnable instances
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
// Start each thread
thread1.start();
thread2.start();
}
}
OUTPUT: Thread: Thread-1 is running.
Thread: Thread-0 is running.
Thread: Thread-0 has completed.
Thread: Thread-1 has completed.
10. 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.
class MyThread extends Thread {
// Constructor
Dept. of CSE, VVIET, Mysuru Page 13
3rd Sem, B.E [CSE] : OOP with JAVA Lab[ BCS306A]
public MyThread(String threadName) {
// Call the base class constructor using super
super(threadName);
// Start the thread
start();
}
// Run method to be executed when the thread starts
@Override
public void run() {
// Displaying the current thread's name
System.out.println("Thread: " + Thread.currentThread().getName() + " is running.");
}
}
public class ThreadExample {
public static void main(String[] args) {
// Displaying the main thread's name
System.out.println("Main Thread: " + Thread.currentThread().getName());
// Create an instance of MyThread (child thread)
MyThread myThread = new MyThread("ChildThread");
// Continue with the main thread's execution
System.out.println("Main Thread continues its execution.");
}
}
OUTPUT: Main Thread: main
Main Thread continues its execution.
Thread: ChildThread is running.
Dept. of CSE, VVIET, Mysuru Page 14