Object oriented programming with java 2023-24
LAB MANUAL OF
OBJECT ORIENTED PROGRAMMING WITH JAVA
FOR 3RD SEMESTER
BRANCH OF COMPUTER SCIENCE(CSE)
SUBJECT CODE: - BCS306A
Artificial intelligence and data science dept. Page 1
Object oriented programming with java 2023-24
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from
import java.util.Scanner;
class AddMatrix{
public static void main(String args[]){
int row, col,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows");
row = in.nextInt();
System.out.println("Enter the number columns");
col = in.nextInt();
int mat1[][] = new int[row][col];
int mat2[][] = new int[row][col];
int res[][] = new int[row][col];
System.out.println("Enter the elements of matrix1");
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
mat1[i][j] = in.nextInt();
Artificial intelligence and data science dept. Page 2
Object oriented programming with java 2023-24
System.out.println();
System.out.println("Enter the elements of matrix2");
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
mat2[i][j] = in.nextInt();
System.out.println();
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
res[i][j] = mat1[i][j] + mat2[i][j] ;
System.out.println("Sum of matrices:-");
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
System.out.print(res[i][j]+"\t");
System.out.println();
Artificial intelligence and data science dept. Page 3
Object oriented programming with java 2023-24
OUTPUT:
Artificial intelligence and data science dept. Page 4
Object oriented programming with java 2023-24
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
class MyStack {
private int arr[];
private int top;
private int capacity;
// Creating a stack
MyStack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
public int pop() {
if (isEmpty()) {
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
Artificial intelligence and data science dept. Page 5
Object oriented programming with java 2023-24
public int getSize() {
return top + 1;
}
public Boolean isEmpty() {
return top == -1;
}
public Boolean isFull() {
return top == capacity - 1;
}
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
public class pushandpop{
public static void main(String[] args) {
MyStack stack = new MyStack(10);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
Artificial intelligence and data science dept. Page 6
Object oriented programming with java 2023-24
OUTPUT:
Artificial intelligence and data science dept. Page 7
Object oriented programming with java 2023-24
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.
class Employee {
private String name;
private String jobTitle;
private double salary;
public Employee(String name, String jobTitle, double salary) {
this.name = name;
this.jobTitle = jobTitle;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public double getSalary() {
return salary;
}
Artificial intelligence and data science dept. Page 8
Object oriented programming with java 2023-24
public void setSalary(double salary) {
this.salary = salary;
}
public void raiseSalary(double percentage) {
salary = salary + salary * percentage / 100;
}
public void printEmployeeDetails() {
System.out.println("Name: " + name);
System.out.println("Job Title: " + jobTitle);
System.out.println("Salary: " + salary);
}
}
public class emp {
public static void main(String[] args) {
Employee employee1 = new Employee("Franziska Waltraud", "HR Manager", 40000);
Employee employee2 = new Employee("Hubertus Andrea", "Software Engineer", 60000);
System.out.println("\nEmployee Details:");
employee1.printEmployeeDetails();
employee2.printEmployeeDetails();
employee1.raiseSalary(8);
employee2.raiseSalary(12);
System.out.println("\nAfter raising salary:");
System.out.println("\n8% for 'Franziska Waltraud':");
employee1.printEmployeeDetails();
System.out.println("\n12% for 'Hubertus Andrea':");
employee2.printEmployeeDetails();
}
}
Artificial intelligence and data science dept. Page 9
Object oriented programming with java 2023-24
OUTPUT:
Artificial intelligence and data science dept. Page 10
Object oriented programming with java 2023-24
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.
class MyPoint {
private int x;
private int y;
Artificial intelligence and data science dept. Page 11
Object oriented programming with java 2023-24
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
// Method to set both x and y
public void setXY(int x, int y) {
this.x = x;
this.y = y;
// Method to get x and y in a 2-element int array
public int[] getXY() {
int[] coordinates = {x, y};
return coordinates;
Artificial intelligence and data science dept. Page 12
Object oriented programming with java 2023-24
// toString method to return a string description of the instance
@Override
public String toString() {
return "(" + x + ", " + y + ")";
// Method to calculate distance from this point to another point
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);
// Another overloaded method to calculate distance from this point to the origin (0,0)
public double distance() {
Artificial intelligence and data science dept. Page 13
Object oriented programming with java 2023-24
return distance(0, 0);
class testmypoint1{
public static void main(String[] args) {
// Test the MyPoint class
MyPoint point1 = new MyPoint(3, 4);
MyPoint point2 = new MyPoint(6, 8);
System.out.println("Point 1: " + point1);
System.out.println("Point 2: " + point2);
System.out.println("Distance between Point 1 and Point 2: " + point1.distance(point2));
System.out.println("Distance from Point 1 to the origin: " + point1.distance());
point1.setXY(1, 2);
System.out.println("Point 1 coordinates after setXY: " + point1.toString());
OUTPUT:
Artificial intelligence and data science dept. Page 14
Object oriented programming with java 2023-24
Artificial intelligence and data science dept. Page 15
Object oriented programming with java 2023-24
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 Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}
class squre extends Shapes {
public void area() {
System.out.println("squre is side * side ");
}
}
class Main {
public static void main(String args[])
{
Shapes myShape = new Shapes(); // Create a Shapes object
Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
Shapes mysqure = new squre();
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
Artificial intelligence and data science dept. Page 16
Object oriented programming with java 2023-24
myShape.area();
mysqure.area();
}
}
OUTPUT:
Artificial intelligence and data science dept. Page 17
Object oriented programming with java 2023-24
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.
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
// Circle.java
// Subclass Circle
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// Rectangle.java
// Subclass Rectangle
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
Artificial intelligence and data science dept. Page 18
Object oriented programming with java 2023-24
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
// Triangle.java
// Subclass Triangle
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
}
Artificial intelligence and data science dept. Page 19
Object oriented programming with java 2023-24
// Main.java
// Main class
public class area {
public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double rs1 = 4.0, rs2 = 6.0;
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Rectangle rectangle = new Rectangle(rs1, rs2);
Triangle triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);
System.out.println("Area of the Circle: " + circle.getArea());
System.out.println("Perimeter of the Circle: " + circle.getPerimeter());
System.out.println("\nSides of the rectangle are: "+rs1+','+rs2);
System.out.println("Area of the Rectangle: " + rectangle.getArea());
System.out.println("Perimeter of the Rectangle: " + rectangle.getPerimeter());
System.out.println("\nSides of the Traiangel are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.getArea());
System.out.println("Perimeter of the Triangle: " + triangle.getPerimeter());
}
}
OUTPUT:
Artificial intelligence and data science dept. Page 20
Object oriented programming with java 2023-24
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 {
// Declare the abstract method "resizeWidth" to resize the width
void resizeWidth(int width);
// Declare the abstract method "resizeHeight" to resize the height
void resizeHeight(int height);
}
// Rectangle.java
// Declare the Rectangle class, which implements the Resizable interface
class Rectangle implements Resizable {
// Declare private instance variables to store width and height
private int width;
private int height;
// Constructor for initializing the width and height
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// Implement the "resizeWidth" method to resize the width
public void resizeWidth(int width) {
this.width = width;
}
// Implement the "resizeHeight" method to resize the height
public void resizeHeight(int height) {
this.height = height;
}
Artificial intelligence and data science dept. Page 21
Object oriented programming with java 2023-24
// Method to print the current width and height of the rectangle
public void printSize() {
System.out.println("Width: " + width + ", Height: " + height);
}
}
// Main.java
// Declare the Main class
public class RESIZEABLE {
public static void main(String args[]) {
// Create an instance of the Rectangle class with an initial size
Rectangle rectangle = new Rectangle(100, 150);
// Print the initial size of the rectangle
rectangle.printSize();
// Resize the rectangle by changing its width and height
rectangle.resizeWidth(150);
rectangle.resizeHeight(200);
// Print the updated size of the rectangle
rectangle.printSize();
}
}
OUTPUT:
Artificial intelligence and data science dept. Page 22
Object oriented programming with java 2023-24
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{
String so = ("This is Outer Class");
void display()
{
System.out.println(so);
}
void test(){
Inner inner = new Inner();
inner.display();
}
//this is an inner class
class Inner{
String si =("This is inner Class");
void display(){
System.out.println(si);
}
}
}
class InnerClassDemo{
public static void main(String args[]){
Outer outer = new Outer();
outer.display();
outer.test();
}
}
Artificial intelligence and data science dept. Page 23
Object oriented programming with java 2023-24
OUTPUT:
Artificial intelligence and data science dept. Page 24
Object oriented programming with java 2023-24
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
//Java program to handle divide by zero exception
import java.util.*;
public class demo9{
public static void main(String[] args) {
int numerator = 7;
int denominator = 3;
try {
int answer = numerator / denominator;
System.out.println("Result: " + answer);
} catch (ArithmeticException ex) {
System.out.println("Error: " + ex.getMessage());
System.out.println("Cannot divide a value by zero.");
}
finally{
System.out.println("change b value.");
}
}
}
OUTPUT:
Artificial intelligence and data science dept. Page 25
Object oriented programming with java 2023-24
10. Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
package mypack;
public class Circle
{
double r;
public void area(double r)
{
System.out.println("Area of the circle = " + (3.14 * r * r));
}
}
//implements the package
import mypack.*;
class Eg
{
public static void main(String a[])
{
Circle c = new Circle();
c.area(6.2);
}
}
OUTPUT:
Artificial intelligence and data science dept. Page 26
Object oriented programming with java 2023-24
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 MyThread implements Runnable {
/**
work of MyThread
*/
@Override
Artificial intelligence and data science dept. Page 27
Object oriented programming with java 2023-24
public void run() {
//works till i is at most 5
for(int i = 1; i<= 5; i++)
{
System.out.println(Thread.currentThread().getName()+" i is " + i);
try {
//sleep current thread for 500 ms
Thread.sleep(500);
} catch (InterruptedException e) {
//print the exception message if occurred
System.out.println(e.getMessage());
}
}
public class IndexNo {
public static void main(String[] args) {
//Common object
MyThread myThread = new MyThread();
Artificial intelligence and data science dept. Page 28
Object oriented programming with java 2023-24
//thread 1
Thread t1 =new Thread(myThread);
//thread2
Thread t2 =new Thread(myThread);
//thread 3
Thread t3 =new Thread(myThread);
//starting all 3 threads now
t1.start();
t2.start();
t3.start();
}
OUTPUT:
Artificial intelligence and data science dept. Page 29
Object oriented programming with java 2023-24
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
{
MyThread()
Artificial intelligence and data science dept. Page 30
Object oriented programming with java 2023-24
{
super ("Using Thread class");
System.out.println("Child thread:" +this);
start();
}
public void run()
{
try
{
for(int i =5;i>0;i--)
{
System.out.println("Child thread" +i);
Thread.sleep (500);
}
} catch (InterruptedException e) { }
System.out.println("exiting child thread..");
}
}
class TestMyThread
{
public static void main(String args[])
{
new MyThread();
try {
for(int k = 5; k<0;k--)
{
System.out.println("Running main thread:" +k);
Thread.sleep(1000);
}
}
catch (InterruptedException e) { }
System.out.println("Exiting main thread . . .");
}
}
Artificial intelligence and data science dept. Page 31
Object oriented programming with java 2023-24
OUTPUT:
Artificial intelligence and data science dept. Page 32