0% found this document useful (0 votes)
8 views18 pages

Java Object-Oriented Programming Guide

The document outlines the curriculum for the Object Oriented Programming with Java course (BCS306A) for the III Semester, detailing the course structure, credits, and examination format. It includes programming experiments that cover various concepts such as matrix addition, stack implementation, employee management, point manipulation, and shape modeling using classes and interfaces. Each experiment is accompanied by example code and expected outputs to illustrate the concepts being taught.

Uploaded by

shaswat042025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Java Object-Oriented Programming Guide

The document outlines the curriculum for the Object Oriented Programming with Java course (BCS306A) for the III Semester, detailing the course structure, credits, and examination format. It includes programming experiments that cover various concepts such as matrix addition, stack implementation, employee management, point manipulation, and shape modeling using classes and interfaces. Each experiment is accompanied by example code and expected outputs to illustrate the concepts being taught.

Uploaded by

shaswat042025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


OBJECT ORIENTED PROGRAMMING WITH JAVA
BCS306A - III Semester

Object Oriented Programming with JAVA Semester 3


Course Code BCS306A CIE Marks 50
Teaching Hours/Week (L: T:P: S) 2:0:2 SEE Marks 50
Total Hours of Pedagogy 28 Hours of Theory + 20 Hours of Practical Total Marks 100
Credits 03 Exam Hours 03
Examination type (SEE) Theory
Programming Experiments (Suggested and are not limited to)
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from
command line arguments).
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main
method to illustrate Stack operations.
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.
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.
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.
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.
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
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.
9. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero using
try, catch, throw and finally.
10. Develop a JAVA program to create a package named mypack and import & implement it in a suitable class.
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).
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.

Page | 1
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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 [Link];

 class AddMatrix {
 public static void main(String args[]) {
 int row, col, i, j;
 Scanner in = new Scanner([Link]);

 [Link]("Enter the number of rows");
 row = [Link]();

 [Link]("Enter the number of columns");
 col = [Link]();

 int mat1[][] = new int[row][col];
 int mat2[][] = new int[row][col];
 int res[][] = new int[row][col];

 [Link]("Enter the elements of matrix1");
 for (i = 0; i < row; i++) {
 for (j = 0; j < col; j++)
 mat1[i][j] = [Link]();
 [Link]();
 }

 [Link]("Enter the elements of matrix2");
 for (i = 0; i < row; i++) {
 for (j = 0; j < col; j++)
 mat2[i][j] = [Link]();
 [Link]();
 }

 for (i = 0; i < row; i++)
 for (j = 0; j < col; j++)
 res[i][j] = mat1[i][j] + mat2[i][j];

 [Link]("Sum of matrices:-");
 for (i = 0; i < row; i++) {
 for (j = 0; j < col; j++)
 [Link](res[i][j] + "\t");
 [Link]();
 }
 }
 }

Page | 2
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
OUTPUT----

Enter the number of rows

Enter the number of columns

Enter the elements of matrix1

123

456

789

Enter the elements of matrix2

234

567

8 9 10

Sum of matrices:-

3 5 7

9 11 13

15 17 19
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.
 // Stack implementation in Java
 class Stack {
 // store elements of stack
 private int arr[];
 // represent top of stack
 private int top;
 // total capacity of the stack
 private int capacity;

 // Creating a stack
 Stack(int size) {
 // initialize the array
 // initialize the stack variables
 arr = new int[size];
 capacity = size;
 top = -1;
 }

Page | 3
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

 // push elements to the top of stack
 public void push(int x) {
 if (isFull()) {
 [Link]("Stack OverFlow");

 // terminates the program
 [Link](1);
 }

 // insert element on top of stack
 [Link]("Inserting " + x);
 arr[++top] = x;
 }

 // pop elements from top of stack
 public int pop() {
 if (isEmpty()) {
 [Link]("STACK EMPTY");
 [Link](1);
 }

 // pop element from top of stack
 return arr[top--];
 }

 // return size of the stack
 public int getSize() {
 return top + 1;
 }

 // check if the stack is empty
 public Boolean isEmpty() {
 return top == -1;
 }

 // check if the stack is full
 public Boolean isFull() {
 return top == capacity - 1;
 }

 // display elements of stack
 public void printStack() {
 for (int i = 0; i <= top; i++) {
 [Link](arr[i] + ", ");
 }
 }

Page | 4
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
 public static void main(String[] args) {
 Stack stack = new Stack(5);

 [Link](1);
 [Link](2);
 [Link](3);

 [Link]("Stack: ");
 [Link]();

 [Link]("\nAfter popping out");
 [Link]();
 [Link]();
 }
 }

OUTPUT—
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out
1, 2,

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 raise Salary (percent) increases the salary
by the given percentage. Develop the Employee class and suitable main method for
demonstration.
public class Employee {
private int id;
private String name;
private double salary;

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


[Link] = id;
[Link] = name;
[Link] = salary;
}

public void raiseSalary(double percent) {


if (percent > 0) {
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
[Link](name + "'s salary raised by " + percent + "%. New
salary: $" + salary);
} else {
[Link]("Invalid percentage. Salary remains unchanged.");

Page | 5
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
}

public String toString() {


return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}

public static void main(String[] arg) {


// Creating an Employee object
Employee employee = new Employee(1, "John Doe", 50000.0);

// Displaying employee details


[Link]("Initial Employee Details:");
[Link](employee);

// Raising Salary by 10%


[Link](10);

// Displaying updated employee details


[Link]("\nEmployee Details after Salary Raise:");
[Link](employee);
}
}

OUTPUT-

Initial Employee Details:

Employee ID: 1, Name: John Doe, Salary: $50000.0

John Doe's salary raised by 10.0%. New salary: $55000.0

Employee Details after Salary Raise:

Employee ID: 1, Name: John Doe, Salary: $55000.0

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)".
Page | 6
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
● A method called distance(int x, int y) that returns the distance from this point to another
point at thegiven (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to
the givenMyPoint 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;

// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}

// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

// Set both x and y


public void setXY(int x, int y)
{ this.x = x;
this.y = y;
}

// Return x and y in a 2-element int array


public int[] getXY() {
int[] xy = {x, y};
return xy;
}

// Returns a string description of the instance in the format "(x, y)"

Page | 7
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

public String toString() {


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

// 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 [Link](xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to another MyPoint instance


public double distance(MyPoint another) {
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to the origin (0, 0)


public double distance() {
return [Link](x * x + y * y);
}
}

///////////////////////////

public class TestMyPoint {


public static void main(String[] args) {
// Create a MyPoint object using default constructor
MyPoint point1 = new MyPoint();
[Link]("Point 1: " + point1); // Output: (0, 0)

// Create a MyPoint object using overloaded constructor


MyPoint point2 = new MyPoint(3, 4);
[Link]("Point 2: " + point2); // Output: (3, 4)

// Set new x and y coordinates using setXY method


[Link](-2, 1);
[Link]("Point 1 after setXY: " + point1); // Output: (-2, 1)

// Get x and y coordinates using getXY method


int[] coordinates = [Link]();
[Link]("Point 2 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")"); // Output: (3, 4)

// Calculate distance between two points


[Link]("Distance between Point 1 and Point 2: " + [Link](point2)); // Output: 5.0

// Calculate distance from Point 1 to a specified point (5, 2)

Page | 8
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

[Link]("Distance from Point 1 to (5, 2): " + [Link](5, 2)); // Output: 7.6157...

// Calculate distance from Point 2 to the origin (0, 0)


[Link]("Distance from Point 2 to the origin: " + [Link]()); // Output: 5.0
}
}

Output-

Point 1: (0, 0)

Point 2: (3, 4)

Point 1 after setXY: (-2, 1)

Point 2 coordinates: (3, 4)

Distance between Point 1 and Point 2: 5.830951894845301

Distance from Point 1 to (5, 2): 7.0710678118654755

Distance from Point 2 to the origin: 5.0


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.

public class TestShapes {


public static void main(String[] args) {
// Demonstrating polymorphism
Shape shape1 = new Circle();
Shape shape2 = new Triangle();
Shape shape3 = new Square();

// Calling draw and erase methods


[Link]();
[Link]();

[Link]();
[Link]();

[Link]();
[Link]();
}

}class Shape {
public void draw()
{ [Link]("Drawing a shape");
}

public void erase()


Page | 9
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
{ [Link]("Erasing a shape");
}
}

class Circle extends Shape {


@Override
public void draw()
{ [Link]("Drawing a circle");
}

@Override
public void erase()
{ [Link]("Erasing a circle");
}
}

class Triangle extends Shape {


@Override
public void draw()
{ [Link]("Drawing a triangle");
}

@Override
public void erase()
{ [Link]("Erasing a triangle");
}
}

class Square extends Shape {


@Override
public void draw()
{ [Link]("Drawing a square");
}

@Override
public void erase()
{ [Link]("Erasing a square");
}
}

OUTPUT-
Drawing a circle
Erasing a circle
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square

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.

Page | 10
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape


{ private double radius;

public Circle(double radius)


{ [Link] = radius;
}

@Override
double calculateArea() {
return [Link] * radius * radius;
}

@Override
double calculatePerimeter()
{ return 2 * [Link] *
radius;
}
}

class Triangle extends Shape


{ private double side1, side2,
side3;

public Triangle(double side1, double side2, double side3)


{ this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s - side1) * (s - side2) * (s - side3));
}

@Override
double calculatePerimeter()
{ return side1 + side2 +
side3;
}
}

public class TestShapes {


public static void main(String[] args) {
// Creating instances of Circle and Triangle
Circle circle = new Circle(5);
Triangle triangle = new Triangle(3, 4, 5);
Page | 11
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

// Calculating area and perimeter for Circle


[Link]("Circle:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());

// Calculating area and perimeter for Triangle


[Link]("\nTriangle:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
}

OUTPUT-

Circle:

Area: 78.53981633974483

Perimeter: 31.41592653589793

Triangle:

Area: 6.0

Perimeter: 12.0
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

public class TestResizable {


public static void main(String[] args)
{ Rectangle rectangle = new Rectangle(10,
20);

[Link]("Original Width: " + [Link]());


[Link]("Original Height: " + [Link]());

[Link](15);
[Link](25);

[Link]("\nResized Width: " + [Link]());


[Link]("Resized Height: " + [Link]());
}
}
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
Page | 12
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}

class Rectangle implements Resizable {


private int width;
private int height;

public Rectangle(int width, int height)


{ [Link] = width;
[Link] = height;
}

public int getWidth()


{ return width;
}

public int getHeight()


{ return height;
}

@Override
public void resizeWidth(int width)
{ [Link] = width;
}
@Override
public void resizeHeight(int height)
{ [Link] = height;
}
}

OUTPUT-

Original Width: 10

Original Height: 20

Resized Width: 15

Resized Height: 25
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() {
[Link]("Outer class display()");
}

class Inner {
void display() {
[Link]("Inner class display()");

Page | 13
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
}
}

public class OuterInnerDemo {


public static void main(String[] args)
{ Outer outerObj = new Outer();
[Link] innerObj = [Link] Inner();

// Calling display() of Outer class


[Link]();

// Calling display() of Inner class


[Link]();
}
}

OUTPUT-

Outer class display()

Inner class display()

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

// Custom exception class for DivisionByZero


class DivisionByZeroException extends Exception
{ public DivisionByZeroException(String message)
{
super(message);
}
}

public class CustomExceptionExample


{ public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;

if (denominator == 0) {
// If denominator is zero, throw the custom exception
throw new DivisionByZeroException("Division by zero is not allowed");
}

int result = numerator / denominator;


[Link]("Result: " + result);

} catch (DivisionByZeroException e) {
// Catch the custom exception and handle it
[Link]("Custom Exception Caught: " + [Link]());
} finally {
Page | 14
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
// Finally block executes whether an exception occurs or not
[Link]("Finally block executed");
}
}
}

Page | 15
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

OUTPUT-

Custom Exception Caught: Division by zero is not allowed

Finally block executed

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

package mypack;

public class MyClass {


public void displayMessage() {
[Link]("This is a message from [Link]");
}
}

/////////////////////////////

import [Link];

public class TestPackage {


public static void main(String[] args)
{ MyClass myObject = new MyClass();
[Link]();
}
}

OUTOUT-
This is a message from [Link]

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


{ private String threadName;

public MyRunnable(String threadName)


{ [Link] = threadName;
}

public void run() {


try {
[Link]("Thread " + threadName + " is starting...");
[Link](500); // Suspend the thread for 500 milliseconds
[Link]("Thread " + threadName + " is running...");
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");

Page | 16
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
[Link]("Thread " + threadName + " is exiting.");
}
}

public class RunnableThreadExample


{ public static void main(String[] args) {
[Link]("Main thread is starting...");

// Create multiple threads using the Runnable interface


Thread thread1 = new Thread(new MyRunnable("Thread
1")); Thread thread2 = new Thread(new
MyRunnable("Thread 2")); Thread thread3 = new
Thread(new MyRunnable("Thread 3"));

// Start each of the newly created threads


[Link]();
[Link]();
[Link]();

[Link]("Main thread is exiting...");


}
}

OUTPUT-
Main thread is starting...
Main thread is exiting...
Thread Thread 1 is starting...
Thread Thread 3 is starting...
Thread Thread 2 is starting...
Thread Thread 3 is running...
Thread Thread 2 is running...
Thread Thread 1 is running...
Thread Thread 2 is exiting.
Thread Thread 3 is exiting.
Thread Thread 1 is exiting.

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(String name) {
super(name); // Calling base class constructor using super
start(); // Starting the thread
}

public void run() {


[Link]("Child Thread is executing");
for (int i = 1; i <= 5; i++) {
[Link]("Child Thread: " + i);
try {
[Link](500); // Suspend thread for 500 milliseconds

Page | 17
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
} catch (InterruptedException e)
{ [Link]("Child Thread interrupted");
}
}
[Link]("Child Thread is exiting");
}
}

public class ThreadExample {


public static void main(String[] args)
{ [Link]("Main Thread is
starting...");

MyThread childThread = new MyThread("Child Thread");

for (int i = 1; i <= 5; i++) {


[Link]("Main Thread: " + i);
try {
[Link](1000); // Suspend main thread for 1 second
} catch (InterruptedException e)
{ [Link]("Main Thread interrupted");
}
}
[Link]("Main Thread is exiting...");
}
}

OUTPUT-
Main Thread is starting...
Child Thread is executing
Main Thread: 1
Child Thread: 1
Child Thread: 2
Main Thread: 2
Child Thread: 3
Child Thread: 4
Main Thread: 3
Child Thread: 5
Child Thread is exiting
Main Thread: 4
Main Thread: 5
Main Thread is exiting...

Page | 18

You might also like