Ooc With Java Lab Manual BCS306A Explanation

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

BLDEA's

V. P. Dr. P. G. Halakatti College of Engineering and Technology,


Vijayapur
Approved by AICTE New Delhi, Recognized by Govt. of Karnataka and Affiliated to VTU Belagavi

LABORATORY MANUAL

COURSE: Object Oriented Programming with JAVA

COURSE CODE: BCS306A

SEMESTER: III
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]

CourseDetails
Year/Semester 2nd Academic Year 2022-23
Course Title Object Oriented Programming With JAVA Course Code BCS306A
Course Type CIE Marks 50
(Theory/Practical SEE Marks 50
Theory
/Integrated) Total Marks 100
Teaching
3:0:2:0 Duration of SEE 3
Hours/Week(L:T:P:S)
Lab Manual Authors Sign- Date

Checked By Sign- Date

Institute Mission:
 To Enrich Students with the essence of science and engineering knowledge, Professional ethics
and social values.
 To instill creativity and Research Temperament to Reach the Greater Heights of Professional
Success.

Institute Vision: To Emerge as a Widely Acknowledged Centre in Technical Education and


Research to Cater the need of Society with a Futuristic outlook.

Program Objectives: The educational objectives of the Mechanical Engineering Program are to
prepare our graduates to:
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2:Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural science, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, cultural, societal and environmental considerations.

PO4: Conduct investigations of complex problems: Use of research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

1
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
PO7:Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of and need
for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams and in multidisciplinary settings.

PO10:Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations and to give and receive
clear instructions.

PO11:Project management and finance: Demonstrate knowledge and understanding of the


engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Course Objectives

●To learn primitive constructs JAVA programming language.


● To understand Object Oriented Programming Features of JAVA
● To gain knowledge on: packages, multithreaded programing and exceptions.

Course Outcomes
At the end of the course, the student will be able to:

CO1 Demonstrate proficiency in writing simple programs involving branching and looping structures.
CO2 Design a class involving data members and methods for the given scenario.
CO3 Apply the concepts of inheritance and interfaces in solving real world problems.
CO4 Use the concept of packages and exception handling in solving complex problem
CO5 Apply concepts of multithreading, auto boxing and enumerations in program development

Dep of CSE 2
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
Assessment Detail
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the SEE minimum
passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be deemed to have satisfied the
academic requirements and earned the credits allotted to each subject/ course if the student secures a minimum of
40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together. CIE for the theory component of the IPCC (maximum marks 50)

● IPCC means practical portion integrated with the theory of the course.

● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.

● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two Tests,
each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other assessment methods
mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the syllabus and the second test after
covering 85-90% of the syllabus.

● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).

● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC. CIE for
the practical component of the IPCC

● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for the
test to be conducted after the completion of all the laboratory sessions.

● On completion of every experiment/program in the laboratory, the students shall be evaluated including
viva-voce and marks shall be awarded on the same day.

● The CIE marks awarded in the case of the Practical component shall be based on the continuous evaluation
of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all experiments’
write-ups are added and scaled down to 15 marks.

● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for 50
marks and scaled down to 10 marks.

● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory component
of IPCC for 25 marks.

● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.
SEE for IPCC Theory SEE will be conducted by University as per the scheduled timetable, with common
question papers for the course (duration 03 hours)

1. The question paper will have ten questions. Each question is set for 20 marks.

2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum
of 3 sub-questions), should have a mix of topics under that module.

3. The students have to answer 5 full questions, selecting one full question from each module.

4. Marks scored by the student shall be proportionally scaled down to 50 Marks The theory portion of the
IPCC shall be for both CIE and SEE, whereas the practical portion will have a CIE component only.
Questions mentioned in the SEE paper may include questions from the practical component. Suggested
Learning Resources: Textbook 15.09.2023 14.09.2023 Annexure-II 5

Dep of CSE 3
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
5 1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021, McGraw-Hill,
ISBN: 9781260463422

Reference Books 1. Programming with Java, 6th Edition, by E Balagurusamy, Mar-2019, McGraw Hill
Education, ISBN: 9789353162337.

2. Thinking in Java, Fourth Edition, by Bruce Eckel, Prentice Hall, 2006


(https://sd.blackball.lv/library/thinking_in_java_4th_edition.pdf) Web links and Video Lectures (e-
Resources):

● Java Tutorial: https://www.geeksforgeeks.org/java/

● Introduction To Programming In Java (by Evan Jones, Adam Marcus and Eugene Wu):
https://ocw.mit.edu/courses/6-092-introduction-to-programming-in-java-january-iap-2010/

● Java Tutorial: https://www.w3schools.com/java/

● Java Tutorial: https://www.javatpoint.com/java-tutorial Activity Based Learning (Suggested Activities)/


Practical Based learning 1. Installation of Java (Refer:
https://www.java.com/en/download/help/index_installing.html) 2. Demonstration of online IDEs like
geeksforgeeks, jdoodle or any other Tools 3. Demonstration of class diagrams for the class abstraction, type
visibility, composition and inheritance Assessment Method

● Programming Assignment / Course Project

Dep of CSE 4
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]

Title of the Programs


Sl No.

Develop a JAVA program to add TWO matrices of suitable order N


1

2 Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.

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)
3
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
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.
4 ● 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.

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
5
(). Demonstrate polymorphism concepts by developing suitable methods, defining member
data and main program.

Develop a JAVA program to create an abstract class Shape with abstract methods
calculate Area() and calculate Perimeter(). Create subclasses Circle and Triangle that
6
extend the Shape class and implement the respective methods to calculate the area and
perimeter of each shape.

Dep of CSE 5
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]

Develop a JAVA program to create an interface Resizable with methods resize Width (int
7 width) and resize Height(int height) that allow an object to be resized. Create a class
Rectangle that implements the Resizable interface and implements the resize methods

Develop a JAVA program to create an outer class with a function display. Create another
8 class inside the outer class named inner with a function called display and call the two
functions in the main class.

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

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

Write a program to illustrate creation of threads using runnable class. (start method start
11 each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).

Develop a program to create a class My Thread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts after
12
this. It can be observed that both main thread and created child thread are executed
concurrently.

Dep of CSE 6
OBJECT ORIENTED PROGRAMMING WITH JAVA

1. Develop a JAVA program to add TWO matrices of suitable order N

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 N of the matrices: ");
int N = scanner.nextInt();
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
int[][] sumMatrix = new int[N][N];

// Input for matrix1


System.out.println("Enter elements of matrix1:");
inputMatrix(matrix1, scanner);

// Input for matrix2


System.out.println("Enter elements of matrix2:");
inputMatrix(matrix2, scanner);

// Adding matrices
sumMatrix = addMatrices(matrix1, matrix2);

// Displaying matrices and their sum


System.out.println("Matrix1:");
displayMatrix(matrix1);
System.out.println("Matrix2:");
displayMatrix(matrix2);
System.out.println("Sum of the matrices:");
displayMatrix(sumMatrix);

scanner.close();
}
// Method to input elements of a matrix
private static void inputMatrix(int[][] matrix, Scanner scanner) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print("Enter element at position (" + i + ", " + j + "): ");
matrix[i][j] = scanner.nextInt();
}
}
}

// Method to add two matrices


private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int N = matrix1.length;
int[][] resultMatrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return resultMatrix;
}

[Type text] Page 7


OBJECT ORIENTED PROGRAMMING WITH JAVA

// Method to display the elements of a matrix


private static void displayMatrix(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();
}
}
}

javac MatrixAddition.java
java MatrixAddition

Enter the order N of the matrices: 2


Enter elements of matrix1:
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 matrix2:
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

Matrix1:
12
34
Matrix2:
56
78
Sum of the matrices:
68
10

[Type text] Page 8


OBJECT ORIENTED PROGRAMMING WITH JAVA

Or

import java.util.Scanner;

public class Main{


public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();
int[][] m1 = new int[n][n];
int[][] m2 = new int[n][n];
int[][] sum = new int[n][n];

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


inputMatrixElements(m1, scanner);

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


inputMatrixElements(m2, scanner);

for (int i = 0; i < n; i++)


for (int j = 0; j < n; j++)
sum[i][j] = m1[i][j] + m2[i][j];

System.out.println("Sum of the matrices:");


displayMatrix(sum);
}

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


for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[0].length; j++)
matrix[i][j] = scanner.nextInt();
}

public static void displayMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int value : row)
System.out.print(value + " ");
System.out.println();
}
}
}

[Type text] Page 9


OBJECT ORIENTED PROGRAMMING WITH JAVA

[Type text] Page 10


OBJECT ORIENTED PROGRAMMING WITH JAVA

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 static final int MAX_SIZE = 10;
private int[] array;
private int top;

public Stack() {
array = new int[MAX_SIZE];
top = -1;
}

public void push(int value) {


if (isFull()) {
System.out.println("Stack is full. Cannot push element " + value);
} else {
array[++top] = value;
System.out.println("Pushed: " + value);
}
}

public void pop() {


if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop element.");

} else {
int poppedValue = array[top--];
System.out.println("Popped: " + poppedValue);
}
}

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == MAX_SIZE - 1;
}

public void display() {


System.out.print("Stack: ");
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}

[Type text] Page 11


OBJECT ORIENTED PROGRAMMING WITH JAVA

public static void main(String[] args) {


Stack stack = new Stack();
stack.push(5);
stack.push(10);
stack.push(15);
stack.display();
stack.pop();
stack.display();
stack.pop();
stack.pop(); // Trying to pop from an empty stack
stack.display();
}
}

O/P:
Pushed: 5
Pushed: 10
Pushed: 15
Stack: 5 10 15
Popped: 15
Stack: 5 10
Popped: 10
Popped: 5
Stack:

[Type text] Page 12


OBJECT ORIENTED PROGRAMMING WITH JAVA

In data structures, a stack is a linear data structure that stores


elements in a last-in, first-out (LIFO) order. This means that the
most recently added element is removed first.

Operations
The two main operations on a stack are push, which adds an item,
and pop, which removes the most recently added item.
Analogy
The name "stack" comes from the physical act of stacking items on top
of each other, like a stack of plates.
Implementation
A stack can be implemented as a singly linked list, with a pointer to the
top element.

[Type text] Page 13


OBJECT ORIENTED PROGRAMMING WITH JAVA

[Type text] Page 14


OBJECT ORIENTED PROGRAMMING WITH JAVA

Applications of stack data structure:


Applications of the stack are enormous and cover a wide range of
domains.
Algorithms such as Depth First Search and Breadth First
Search use stack to traverse the graph.
Memory Management:
The call stack is responsible for keeping a record of all function
calls and returns, as well as for allocating and de allocating
memory for each function call.
Expression Evaluation:
Stacks are the primary data structure utilized by programming
languages for evaluating expressions. When using postfix
notation, the operands are placed on top of the stack, and the
operators are executed once they are reached.
History of the Browser:
The back button seen in web browsers utilizes a stack to preserve
a record of the sites that have been visited in the past. Each new
page is placed on the top of the stack, and the most recent page
is removed from the stack if the user clicks the back button on
their browser.
Undo Redo in Editors:
Stacks are a frequently utilized data structure in software
systems, and one of their primary functions is to implement the
undo and redo functions. Each action is added to the stack, and
the user can undo any of their prior actions by removing things
from the stack in the order in which they were added.
Parsing:
The usage of stacks in parsing algorithms helps to ensure that the
operations are performed in the appropriate order. For instance,
the shunting yard technique employs the utilization of two stacks
in order to convert infix notation into postfix notation.
Text Editors:
Stacks are utilized in the implementation of text editing
capabilities such as undo/redo, copy/paste, and indentation in
text editors. For example, one use of the indentation stack is to

[Type text] Page 15


OBJECT ORIENTED PROGRAMMING WITH JAVA

monitor the level of an indentation that has been applied to a


portion of code.

Recursive functions:
When a function is called recursively on a computer, the stack is
used to keep track of each individual function call made by the
computer. As a function is finished being executed, its contents
are “popped” off the stack, and each new call is “pushed” onto
the stack.

[Type text] Page 16


OBJECT ORIENTED PROGRAMMING WITH JAVA

3. A class called Employee, which models an employee with an ID, name and salary. 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;

// Constructor
public Employee(int empId, String name, double salary) {
this.empId = empId;
this.name = name;
this.salary = salary;
}

// Method to raise the salary by a given percentage


public void raiseSalary(double percent) {
this.salary += this.salary * (percent / 100);
}

// Method to display employee details


public void displayDetails() {
System.out.println("Employee ID: " + empId);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}

// Main method for demonstration


public static void main(String[] args) {
// Creating an Employee object
Employee emp = new Employee(1, "John Henry", 50000);

// Displaying initial details


System.out.println("Before raise:");
emp.displayDetails();

// Raising the salary by 10%


emp.raiseSalary(10);

// Displaying details after the raise


System.out.println("\n After raise:");
emp.displayDetails();
}
}

[Type text] Page 17


OBJECT ORIENTED PROGRAMMING WITH JAVA

Output:

Before raise:
Employee ID: 1
Name: John Henry
Salary: 50000.0

After raise:
Employee ID: 1
Name: John Henry
Salary: 55000.0

[Type text] Page 18


OBJECT ORIENTED PROGRAMMING WITH JAVA

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.

File Name: MyPoint.java (In the same Project folder)

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;
}

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


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

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


public String toString( ) {
return "(" + x + ", " + y + ")";
}

[Type text] Page 19


OBJECT ORIENTED PROGRAMMING WITH JAVA

// Calculate distance from this point to another point at (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);
}

// Calculate distance from this point to another MyPoint instance (another)


public double distance(MyPoint another) {
return distance(another.x, another.y);
}

// Calculate distance from this point to the origin (0,0)


public double distance() {
return distance(0, 0);
}
}

File Name: TestMyPoint.java (In the same Project folder)


/*Create Another File with the name as TestMyPoint*/

public class TestMyPoint {


public static void main(String[] args) {
// Creating MyPoint objects using different constructors
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);

// Testing setXY and getXY methods


point1.setXY(1, 2);
System.out.println("Point1 coordinates after setXY: " + point1.getXY()[0] + ", " + point1.getXY()[1]);

// Testing toString method


System.out.println("Point2 coordinates: " + point2.toString());

// Testing distance methods


System.out.println("Distance from Point1 to Point2: " + point1.distance(point2));
System.out.println("Distance from Point2 to Origin: " + point2.distance());
}
}

O/P:
Point1 coordinates after setXY: 1, 2
Point2 coordinates: (3, 4)
Distance from Point1 to Point2: 2.8284271247461903
Distance from Point2 to Origin: 5.0

[Type text] Page 20


OBJECT ORIENTED PROGRAMMING WITH JAVA

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 {
protected String name;

public Shape(String name) {


this.name = name;
}

public void draw() {


System.out.println("Drawing a " + name);
}

public void erase() {


System.out.println("Erasing a " + name);
}
}

class Circle extends Shape {


private double radius;

public Circle(String name, double radius) {


super(name);
this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}

@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}

class Triangle extends Shape {


private double base;
private double height;

public Triangle(String name, double base, double height) {


super(name);
this.base = base;
this.height = height;
}

[Type text] Page 21


OBJECT ORIENTED PROGRAMMING WITH JAVA

@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}

@Override
public void erase() {
System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}

class Square extends Shape {


private double side;

public Square(String name, double side) {


super(name);
this.side = side;
}

@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}

@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}

public class ShapeDemo {


public static void main(String[] args) {
Shape[] shapes = new Shape[3];

shapes[0] = new Circle("Circle", 5.0);


shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);
for (Shape shape : shapes) {
shape.draw();
shape.erase();
System.out.println();
}
}
}

O/P:
$ java ShapeDemo
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0

Drawing a triangle with base 4.0 and height 6.0


Erasing a triangle with base 4.0 and height 6.0

[Type text] Page 22


OBJECT ORIENTED PROGRAMMING WITH JAVA

Drawing a square with side length 3.0


Erasing a square with side length 3.0

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 {


abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

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;
}

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

@Override
double calculatePerimeter() {

[Type text] Page 23


OBJECT ORIENTED PROGRAMMING WITH JAVA

return side1 + side2 + side3;


}
}

public class ShapeDemo {


public static void main(String[] args) {
// Creating Circle and Triangle objects
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);

// Calculating and displaying area and perimeter


System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

System.out.println("\nTriangle Area: " + triangle.calculateArea());


System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}

O/P:
$ java ShapeDemo
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793

Triangle Area: 6.0


Triangle Perimeter: 12.0

[Type text] Page 24


OBJECT ORIENTED PROGRAMMING WITH JAVA

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

// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Rectangle class implementing Resizable interface


class Rectangle implements Resizable {
private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

// Implementation of Resizable interface


@Override
public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}

@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}

// Additional methods for Rectangle class


public int getWidth() {
return width;
}

public int getHeight() {


return height;
}

public void displayInfo() {


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

[Type text] Page 25


OBJECT ORIENTED PROGRAMMING WITH JAVA

// Main class to test the implementation


public class ResizeDemo {
public static void main(String[] args) {
// Creating a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);

// Displaying the original information


System.out.println("Original Rectangle Info:");
rectangle.displayInfo();

// Resizing the rectangle


rectangle.resizeWidth(15);
rectangle.resizeHeight(8);

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}

O/P:
$ java ResizeDemo
Original Rectangle Info:
Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 8

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8

[Type text] Page 26


OBJECT ORIENTED PROGRAMMING WITH JAVA

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 class display method");
}

class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args) {
// Create an instance of the Outer class
Outer outer = new Outer();

// Call the display method of the Outer class


outer.display();

// Create an instance of the Inner class (nested inside Outer)


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

// Call the display method of the Inner class


inner.display();
}
}

O/P:
$ java OuterInnerDemo
Outer class display method
Inner class display method

[Type text] Page 27


OBJECT ORIENTED PROGRAMMING WITH JAVA

9. 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
{
public DivisionByZeroException(String message)
{
super(message);
}
}

public class CustomExceptionDemo


{
// Method to perform division and throw custom exception if denominator is zero
static double divide(int numerator, int denominator) throws DivisionByZeroException {
if (denominator == 0)
{
throw new DivisionByZeroException("Cannot divide by zero!");
}
return (double) numerator / denominator;
}

public static void main(String[] args) {


int numerator = 10;
int denominator = 0;

try
{
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e)
{
System.out.println("Exception caught: " + e.getMessage());
}
finally
{
System.out.println("Finally block executed");
}
}
}

O/P:
$ java CustomExceptionDemo

[Type text] Page 28


OBJECT ORIENTED PROGRAMMING WITH JAVA

Exception caught: Cannot divide by zero!


Finally block executed

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

// Inside a folder named 'mypack'


package mypack;

public class MyPackageClass {


public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}

// New utility method


public static int addNumbers(int a, int b) {
return a + b;
}
}
let’s create the main program in a different file outside the mypack folder:

PackageDemo class using mypack Package

// Main program outside the mypack folder


import mypack.MyPackageClass;
//import mypack.*;

public class PackageDemo {


public static void main(String[] args) {
// Creating an instance of MyPackageClass from the mypack package
MyPackageClass myPackageObject = new MyPackageClass();

// Calling the displayMessage method from MyPackageClass


myPackageObject.displayMessage();

// Using the utility method addNumbers from MyPackageClass


int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);

[Type text] Page 29


OBJECT ORIENTED PROGRAMMING WITH JAVA

}
}
To compile and run this program, you need to follow these steps:
Organize your directory structure as follows:

project-directory/
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
Compile the files:
javac mypack/MyPackageClass.java
javac PackageDemo.java

O/P:
$ java PackageDemo
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8

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

class MyRunnable implements Runnable {


private volatile boolean running = true;

@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}

public void stopThread() {


running = false;
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
// Create five instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();

[Type text] Page 30


OBJECT ORIENTED PROGRAMMING WITH JAVA

// Create five threads and associate them with MyRunnable instances


Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);

// Start the threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();

// Sleep for a while to allow the threads to run


try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop the threads gracefully


myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
}
}

O/P:
$ java RunnableThreadExample
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.

[Type text] Page 31


OBJECT ORIENTED PROGRAMMING WITH JAVA

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 {


// Constructor calling base class constructor using super
public MyThread(String name) {
super(name);
start(); // Start the thread in the constructor
}

// The run method that will be executed when the thread starts
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}

public class ThreadConcurrentExample {


public static void main(String[] args) {
// Create an instance of MyThread
MyThread myThread = new MyThread("Child Thread");

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

[Type text] Page 32


OBJECT ORIENTED PROGRAMMING WITH JAVA

System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);


try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}

O/P:
$ java ThreadConcurrentExample
main Thread Count: 1
Child Thread Count: 1
main Thread Count: 2
Child Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5

[Type text] Page 33

You might also like