You are on page 1of 24

Object oriented programming with Java Department of CSE-Data Science

1.Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).

import java.util.Scanner;

public class MatrixAddition {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the order of matrices (N): ");

int N = scanner.nextInt();

int[][] matrixA = new int[N][N];

int[][] matrixB = new int[N][N];

System.out.println("Enter elements of matrix A:");

inputMatrixElements(matrixA, scanner);

System.out.println("Enter elements of matrix B:");

inputMatrixElements(matrixB, scanner);

System.out.println("Matrix A:");

printMatrix(matrixA);

System.out.println("Matrix B:");

printMatrix(matrixB);

int[][] sumMatrix = addMatrices(matrixA, matrixB);

System.out.println("Sum of Matrix A and Matrix B:");

printMatrix(sumMatrix);

scanner.close();

private static void inputMatrixElements(int[][] matrix, Scanner scanner) {

int N = matrix.length;

for (int i = 0; i < N; i++) {

ACS College Of Engineering Page 1


Object oriented programming with Java Department of CSE-Data Science

for (int j = 0; j < N; j++) {

System.out.print("Enter element at position [" + i + "][" + j + "]: ");

matrix[i][j] = scanner.nextInt();

}}

private static int[][] addMatrices(int[][] matrixA, int[][] matrixB) {

int N = matrixA.length;

int[][] sumMatrix = new int[N][N];

for (int i = 0; i < N; i++) {

for (int j = 0; j < N; j++) {

sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j];

return sumMatrix;

private static void printMatrix(int[][] matrix) {

int N = matrix.length;

for (int i = 0; i < N; i++) {

for (int j = 0; j < N; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

System.out.println();

ACS College Of Engineering Page 2


Object oriented programming with Java Department of CSE-Data Science

Output: Enter the order of matrices (N): 2

Enter elements of matrix A:

Enter element at position [0][0]: 1

Enter element at position [0][1]: 2

Enter element at position [1][0]: 3

Enter element at position [1][1]: 4

Enter elements of matrix B:

Enter element at position [0][0]: 5

Enter element at position [0][1]: 6

Enter element at position [1][0]: 7

Enter element at position [1][1]: 8

Matrix A:

12

34

Matrix B:

56

78

Sum of Matrix A and Matrix B:

68

10 12

ACS College Of Engineering Page 3


Object oriented programming with Java Department of CSE-Data Science

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[] stackArray;

private int top;

private final int maxSize;

public Stack() {

maxSize = 10;

stackArray = new int[maxSize];

top = -1;

public boolean isEmpty() {

return (top == -1);

public boolean isFull() {

return (top == maxSize - 1);

public void push(int value) {

if (isFull()) {

System.out.println("Stack is full. Cannot push " + value);

} else {

top++;

stackArray[top] = value;

System.out.println(value + " pushed to stack");

ACS College Of Engineering Page 4


Object oriented programming with Java Department of CSE-Data Science

public int pop() {

if (isEmpty()) {

System.out.println("Stack is empty. Cannot pop");

return -1; // Return a default value indicating failure

} else {

int poppedValue = stackArray[top];

top--;

return poppedValue;

public int peek() {

if (isEmpty()) {

System.out.println("Stack is empty. No peek value");

return -1; // Return a default value indicating failure

} else {

return stackArray[top];

public static void main(String[] args) {

Stack stack = new Stack();

// Pushing elements to the stack

stack.push(5);

stack.push(10);

stack.push(15);

stack.push(20);

// Popping elements from the stack

ACS College Of Engineering Page 5


Object oriented programming with Java Department of CSE-Data Science

System.out.println("Popped element: " + stack.pop());

System.out.println("Popped element: " + stack.pop());

// Peek at the top element without removing it

System.out.println("Top element: " + stack.peek());

Output: Pushed: 5

Pushed: 10

Pushed: 15

Stack elements:

15

10

Popped: 15

Stack elements:

10

Popped: 10

Popped: 5

Stack is empty.

ACS College Of Engineering Page 6


Object oriented programming with Java Department of CSE-Data Science

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 {

private int empId;

private String name;

private double salary;

public Employee(int empId, String name, double salary) {

this.empId = empId;

this.name = name;

this.salary = salary;

public void raiseSalary(double percent) {

this.salary *= (1 + percent / 100);

public void displayDetails() {

System.out.println("Employee ID: " + empId);

System.out.println("Name: " + name);

System.out.println("Salary: $" + salary);

public static void main(String[] args) {

// Creating an Employee object

Employee emp = new Employee(1, "John Doe", 50000);

// Displaying initial details

System.out.println("Initial Details:");

emp.displayDetails();

ACS College Of Engineering Page 7


Object oriented programming with Java Department of CSE-Data Science

// Increasing salary by 10%

double percentIncrease = 10;

emp.raiseSalary(percentIncrease);

// Displaying updated details

System.out.println("\nAfter Salary Raise:");

emp.displayDetails();

Output: Before raise:

Employee ID: 1

Employee Name: John Doe

Employee Salary: $50000.0

After 10% raise:

Employee ID: 1

Employee Name: John Doe

Employee Salary: $55000.0

ACS College Of Engineering Page 8


Object oriented programming with Java Department of CSE-Data Science

4) A class called MyPoint, which models a 2D point with x and y coordinates, is


designed as follows:

● Two instance variables x (int) and y (int).

● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).

● A overloaded constructor that constructs a point with the given x and y coordinates.

● A method setXY() to set both x and y.

● A method getXY() which returns the x and y in a 2-element int array.

● 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.

public class MyPoint {

private int x;

private int y;

public MyPoint() {

this.x = 0;

this.y = 0;

public MyPoint(int x, int y) {

this.x = x;

this.y = y;

public void setXY(int x, int y) {

ACS College Of Engineering Page 9


Object oriented programming with Java Department of CSE-Data Science

this.x = x;

this.y = y;

public int[] getXY() {

return new int[]{x, y};

public String toString() {

return "(" + x + ", " + y + ")";

public double distance(int x, int y) {

int xDiff = this.x - x;

int yDiff = this.y - y;

return Math.sqrt(xDiff * xDiff + yDiff * yDiff);

public double distance(MyPoint another) {

return distance(another.x, another.y);

public double distance() {

return distance(0, 0);

public class TestMyPoint {

public static void main(String[] args) {

// Testing MyPoint class methods

MyPoint point1 = new MyPoint();

MyPoint point2 = new MyPoint(3, 4);

ACS College Of Engineering Page 10


Object oriented programming with Java Department of CSE-Data Science

point1.setXY(5, 7);

System.out.println("point1 coordinates: " + point1.getXY());

System.out.println("point1: " + point1);

System.out.println("point2: " + point2);

System.out.println("Distance between point1 and (3,4): " + point1.distance(3, 4));

System.out.println("Distance between point1 and point2: " + point1.distance(point2));

System.out.println("Distance from point1 to origin: " + point1.distance());

Output: Coordinates of point1: [5, 7]

Point1: (5, 7)

Point2: (3, 4)

Distance between point1 and (3,4): 4.242640687119285

Distance between point1 and point2: 3.605551275463989

Distance from point1 to origin: 8.602325267042627

ACS College Of Engineering Page 11


Object oriented programming with Java Department of CSE-Data Science

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.

class Shape {

public void draw() {

System.out.println("Drawing shape");

public void erase() {

System.out.println("Erasing shape");

class Circle extends Shape {

@Override

public void draw() {

System.out.println("Drawing Circle");

@Override

public void erase() {

System.out.println("Erasing Circle");

class Triangle extends Shape {

@Override

public void draw() {

System.out.println("Drawing Triangle");

ACS College Of Engineering Page 12


Object oriented programming with Java Department of CSE-Data Science

@Override

public void erase() {

System.out.println("Erasing Triangle");

class Square extends Shape {

@Override

public void draw() {

System.out.println("Drawing Square");

@Override

public void erase() {

System.out.println("Erasing Square");

public class Main {

public static void main(String[] args) {

Shape circle = new Circle();

Shape triangle = new Triangle();

Shape square = new Square();

// Demonstrate polymorphism: Same method calls on different objects yield different


results

circle.draw();

circle.erase();

triangle.draw();

triangle.erase();

ACS College Of Engineering Page 13


Object oriented programming with Java Department of CSE-Data Science

square.draw();

square.erase();

Output: Drawing Circle

Erasing Circle

Drawing Triangle

Erasing Triangle

Drawing Square

Erasing Square

ACS College Of Engineering Page 14


Object oriented programming with Java Department of CSE-Data Science

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.

class Rectangle {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

public double calculateArea() {

return length * width;

public double calculatePerimeter() {

return 2 * (length + width);

public class Main {

public static void main(String[] args) {

// Creating a rectangle object with length 5 and width 3

Rectangle rectangle = new Rectangle(5, 3);

// Calculating and printing the area of the rectangle

double area = rectangle.calculateArea();

System.out.println("Area of the rectangle: " + area);

// Calculating and printing the perimeter of the rectangle

double perimeter = rectangle.calculatePerimeter();

ACS College Of Engineering Page 15


Object oriented programming with Java Department of CSE-Data Science

System.out.println("Perimeter of the rectangle: " + perimeter);

Output: Circle Area: 78.53981633974483

Circle Perimeter: 31.41592653589793

Triangle Area: 6.0

Triangle Perimeter: 12.0

ACS College Of Engineering Page 16


Object oriented programming with Java Department of CSE-Data Science

7) 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.

interface Resizable {

void resizeWidth(int width);

void resizeHeight(int height);

class Rectangle implements Resizable {

private int width;

private int height;

public Rectangle(int width, int height) {

this.width = width;

this.height = height;

public void resizeWidth(int width) {

this.width = width;

public void resizeHeight(int height) {

this.height = height;

public void display() {

System.out.println("Rectangle Width: " + width + ", Height: " + height);

ACS College Of Engineering Page 17


Object oriented programming with Java Department of CSE-Data Science

public class TestResizable {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle(10, 20);

rectangle.display();

rectangle.resizeWidth(15);

rectangle.resizeHeight(25);

rectangle.display();

Output: Rectangle Width: 10, Height: 20

Rectangle Width: 15, Height: 25

ACS College Of Engineering Page 18


Object oriented programming with Java Department of CSE-Data Science

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.

class Outer {

void display() {

System.out.println("Outer display method");

class Inner {

void display() {

System.out.println("Inner display method");

public class Main {

public static void main(String[] args) {

Outer outer = new Outer();

Outer.Inner inner = outer.new Inner();

outer.display(); // Calls Outer class's display method

inner.display(); // Calls Inner class's display method

Output: Outer display method

Inner display method

ACS College Of Engineering Page 19


Object oriented programming with Java Department of CSE-Data Science

9) Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

class DivisionByZeroException extends Exception {

public DivisionByZeroException(String message) {

super(message);

public class Main {

public static void main(String[] args) {

int dividend = 20;

int divisor = 0;

double result;

try {

if (divisor == 0) {

throw new DivisionByZeroException("Division by zero is not allowed");

result = dividend / divisor;

System.out.println("Result: " + result);

} catch (DivisionByZeroException e) {

System.out.println("Caught Exception: " + e.getMessage());

} finally {

System.out.println("Finally block executed");

}}}

Output: Caught Exception: Division by zero is not allowed

Finally block executed

ACS College Of Engineering Page 20


Object oriented programming with Java Department of CSE-Data Science

10) Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.

package mypack;

public class MyPackageClass {

public void display() {

System.out.println("This is a method from the MyPackageClass in mypack package.");

import mypack.MyPackageClass;

public class Main {

public static void main(String[] args) {

MyPackageClass obj = new MyPackageClass();

obj.display();

Output: This is a method from the MyPackageClass in mypack package.

ACS College Of Engineering Page 21


Object oriented programming with Java Department of CSE-Data Science

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).

class MyRunnable implements Runnable {

public void run() {

try {

System.out.println(Thread.currentThread().getName() + " is running.");

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " was interrupted.");

public class ThreadCreation {

public static void main(String[] args) {

// Creating threads using the Runnable interface

Thread thread1 = new Thread(new MyRunnable(), "Thread 1");

Thread thread2 = new Thread(new MyRunnable(), "Thread 2");

// Starting threads

thread1.start();

thread2.start();

Output: Thread 1 is running.

Thread 2 is running

ACS College Of Engineering Page 22


Object oriented programming with Java Department of CSE-Data Science

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.

class MyThread extends Thread {

public MyThread() {

super(); // Calls the Thread class constructor

start(); // Starts the thread

public void run() {

System.out.println("Child Thread is running.");

public class ThreadDemo {

public static void main(String[] args) {

// Creating an instance of MyThread

MyThread myThread = new MyThread();

System.out.println("Main Thread is running concurrently.");

Output: Child Thread is running.

Main Thread is running concurrently.

ACS College Of Engineering Page 23


Object oriented programming with Java Department of CSE-Data Science

ACS College Of Engineering Page 24

You might also like