0% found this document useful (0 votes)
46 views40 pages

BCS306A Lab-Manual - Final

lab manual

Uploaded by

Rohi B
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)
46 views40 pages

BCS306A Lab-Manual - Final

lab manual

Uploaded by

Rohi B
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
You are on page 1/ 40

Academic Year 2024 – 2025 (ODD Semester)

LAB MANUAL

Object Oriented Programming with JAVA


(LABORATORY COMPONENT)
BCS306A
III Semester CSE(DS)

Prepared By

Mamatha C R
Asso. Professor
Dept. of CSE(DS)
Vision and Mission of the Institute
Vision
To become a leading institute for quality technical education and research with ethical values.
Mission
M1: To continually improve quality education system that produces thinking engineers having
good technical capabilities with human values.
M2: To nurture a good eco-system that encourages faculty and students to engage in meaningful
research and development.
M3: To strengthen industry institute interface for promoting team work, internship and
entrepreneurship.
M4: To enhance educational opportunities to the rural and weaker sections of the society to equip
with practical skills to face the challenges of life.

Vision and Mission of the Department


Vision
To become a leading department engaged in quality education and research in the field of
computer science and engineering.

Mission
M1: To nurture a positive environment with state of art facilities conducive for deep learning
and meaningful research and development.

M2: To enhance interaction with industry for promoting collaborative research in emerging
technologies.
M3: To strengthen the learning experiences enabling the students to become ethical professionals
with good interpersonal skills, capable of working effectively in multi-disciplinary teams.
PROGRAM EDUCATIONAL OBJECTIVES (PEOS)
PEO 1: Successful and ethical professionals in IT and ITES industries contributing to societal
progress.
PEO 2: Engaged in life-long learning, adapting to changing technological scenarios.
PEO 3: Communicate and work effectively in diverse teams and exhibit leadership qualities.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO 1: Analyze, design, implement and test innovative application software systems to meet the
specified requirements.
PSO 2: Understand and use systems software packages.
PSO 3: Understand the organization and architecture of digital computers, embedded systems
and computer networks.

PROGRAM OUTCOMES (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. 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, and the cultural, societal, and environmental
consideration.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. 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.
6. 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.
7. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. 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 give
and receive clear instructions.
11. 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.
12. 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.
SYLLABUS
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.
Table of contents
Exp Experiments Page
. No.
No.
1

10

11

12
OOPS with Java Laboratory 2024-25

Program 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) {
// Check if the number of command line arguments is correct
if (args.length != 1) {
System.out.println("Usage: java MatrixAddition <order_N>");
return;
}
// Parse the command line argument to get the order N
int N = Integer.parseInt(args[0]);
// Check if N is a positive integer
if (N <= 0) {
System.out.println("Please provide a valid positive integer for the order N.");
return;
}
// Create two matrices of order N
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
System.out.println("Matrix 1");
fillMatrix(matrix1);
System.out.println("Matrix 2");
fillMatrix(matrix2);
// Print the matrices
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("\nMatrix 2:");
printMatrix(matrix2);
// Add the matrices

Dept. of CSE(DS), Vemana IT 1


OOPS with Java Laboratory 2024-25

int[][] resultMatrix = addMatrices(matrix1, matrix2);


// Print the result matrix
System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
printMatrix(resultMatrix);
}
// Helper method to fill a matrix with sequential values
private static void fillMatrix(int[][] matrix) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++) {
System.out.println("Enter "+matrix[i].length+" elements of row " +(i+1));
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = scan.nextInt();
}
}
}
// Helper 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;
}
// Helper method to print a matrix
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + "\t");

Dept. of CSE(DS), Vemana IT 2


OOPS with Java Laboratory 2024-25

}
System.out.println();
}
}
}

Follow this step to pass command line arguments in eclipse,


 Click Run  Run Configurations  Arguments
 Under Program arguments type order of matrix such as 2 or 3.
 Click Apply and Close
 Run the application
Output

Dept. of CSE(DS), Vemana IT 3


OOPS with Java Laboratory 2024-25

[sample program]
package chitra;

public class Addmatrix {

public static void main(String[] args)


{
int n = Integer.parseInt (args[0]);
int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] sum = new int[n][n];
// Initialize matrices with some values, for example, i+j
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
matrix1[i][j] = i + j;
matrix2[i][j] = i + j;
System.out.print("matrix1["+i+"]["+j+"]="+matrix1[i][j]+" ");
System.out.println("matrix2["+i+"]["+j+"]="+matrix2[i][j]+" ");
}
}
// Add the matrices
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Print the result
System.out.println ("Sum of matrices is: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print (sum[i][j] + " ");
}
System.out.println ();
}}}
matrix1[0][0]=0 matrix2[0][0]=0
matrix1[0][1]=1 matrix2[0][1]=1

Dept. of CSE(DS), Vemana IT 4


OOPS with Java Laboratory 2024-25

matrix1[1][0]=1 matrix2[1][0]=1
matrix1[1][1]=2 matrix2[1][1]=2
Sum of matrices is:
0 2
2 4
Program 2
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main
method to illustrate Stack operations.
import java.util.Scanner;
public class Stack {
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
public void push(int value) {
if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity

Dept. of CSE(DS), Vemana IT 5


OOPS with Java Laboratory 2024-25

}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}
public void display() {
if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = top; i >= 0; --i) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");

Dept. of CSE(DS), Vemana IT 6


OOPS with Java Laboratory 2024-25

System.out.println("4. Display Stack Contents");


System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();
}
}
Output
Stack Menu:

Dept. of CSE(DS), Vemana IT 7


OOPS with Java Laboratory 2024-25

1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 9
Pushed: 9

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 8
Pushed: 8

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 7
Pushed: 7

Stack Menu:
1. Push

Dept. of CSE(DS), Vemana IT 8


OOPS with Java Laboratory 2024-25

2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 6
Pushed: 6

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 4
Stack Contents: 6 7 8 9

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 3
Peeked: 6

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents

Dept. of CSE(DS), Vemana IT 9


OOPS with Java Laboratory 2024-25

0. Exit
Enter your choice: 2
Popped: 6

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 7

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 8

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 9

Dept. of CSE(DS), Vemana IT 10


OOPS with Java Laboratory 2024-25

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Stack Underflow! Cannot pop from an empty stack.

Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 0
Exiting the program. Goodbye!

Program 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.
import java.util.Scanner;
public class Emloyee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.name = name;
this.id = id;
this.salary = salary;

Dept. of CSE(DS), Vemana IT 11


OOPS with Java Laboratory 2024-25

}
public void display() {
System.out.println("Id: " + id);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
public void raiseSalary(double percentage) {
salary = salary + (salary * percentage / 100);
}
public static void main(String[] args) {
int id;
String name;
double salary, percentage;

Scanner scan= new Scanner(System.in);


System.out.println(“Enter Employee Id”);
id = scan.nextInt();
System.out.println("Enter Employee Name");
name = scan.next();
System.out.println("Enter Salary");
salary = scan.nextDouble();
Employee e1 = new Employee(id, name, salary);
System.out.println("Employee Details");
e1.display();
System.out.println("\nEnter the percentage to raise the salary");
percentage = scan.nextDouble ();
e1.raiseSalary(percentage);
System.out.println("\nAfter raising salary");
e1.display();
}
}

Dept. of CSE(DS), Vemana IT 12


OOPS with Java Laboratory 2024-25

Output
Enter Employee Id
200
Enter Employee Name
Gopal
Enter Salary
100000
Employee Details
Id: 200
Name: Gopal
Salary: 100000.0

Enter the percentage to raise the salary


30

After raising salary


Id: 200
Name: Gopal
Salary: 130000.0

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

Dept. of CSE(DS), Vemana IT 13


OOPS with Java Laboratory 2024-25

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() {
int arr[] = {x,y};
return arr;
}

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


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

Dept. of CSE(DS), Vemana IT 14


OOPS with Java Laboratory 2024-25

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

Dept. of CSE(DS), Vemana IT 15


OOPS with Java Laboratory 2024-25

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());
}
}
Output
Point1 coordinates after setXY: 1, 2
Point2 coordinates: (3, 4)
Distance from Point1 to Point2: 2.8284271247461903
Distance from Point2 to Origin: 5.0

Program 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.
// Base class representing a general Shape
class Shape {
protected String name; // Name of the shape

// Constructor that initializes the shape's name


public Shape(String name) {
this.name = name;
}

// Method to draw the shape


public void draw() {
System.out.println("Drawing a " + name);
}

Dept. of CSE(DS), Vemana IT 16


OOPS with Java Laboratory 2024-25

// Method to erase the shape


public void erase() {
System.out.println("Erasing a " + name);
}
}

// Circle class that extends Shape


class Circle extends Shape {
private double radius; // Radius of the circle

// Constructor that initializes the name and radius of the circle


public Circle(String name, double radius) {
super(name); // Call to the superclass constructor
this.radius = radius; // Initialize radius
}

// Override draw method for Circle


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

// Override erase method for Circle


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

// Triangle class that extends Shape


class Triangle extends Shape {

Dept. of CSE(DS), Vemana IT 17


OOPS with Java Laboratory 2024-25

private double base; // Base of the triangle


private double height; // Height of the triangle

// Constructor that initializes the name, base, and height of the triangle
public Triangle(String name, double base, double height) {
super(name); // Call to the superclass constructor
this.base = base; // Initialize base
this.height = height; // Initialize height
}

// Override draw method for Triangle


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

// Override erase method for Triangle


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

// Square class that extends Shape


class Square extends Shape {
private double side; // Side length of the square

// Constructor that initializes the name and side length of the square
public Square(String name, double side) {
super(name); // Call to the superclass constructor
this.side = side; // Initialize side length

Dept. of CSE(DS), Vemana IT 18


OOPS with Java Laboratory 2024-25

// Override draw method for Square


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

// Override erase method for Square


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

// Main class to demonstrate the shape classes


public class ShapeDemo {
public static void main(String[] args) {
// Create an array of Shape references
Shape[] shapes = new Shape[3];

// Initialize shapes with specific instances


shapes[0] = new Circle("Circle", 5.0);
shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);

// Loop through each shape and call draw and erase methods
for (Shape shape : shapes) {
shape.draw(); // Draw the shape
shape.erase(); // Erase the shape
System.out.println(); // Print a blank line for better readability

Dept. of CSE(DS), Vemana IT 19


OOPS with Java Laboratory 2024-25

}
}
}
Output:
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

Drawing a square with side length 3.0


Erasing a square with side length 3.0

Program 06
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 representing a generic shape


abstract class Shape {
// Abstract method to calculate the area of the shape
abstract double calculateArea();

// Abstract method to calculate the perimeter of the shape


abstract double calculatePerimeter();
}

// Class representing a Circle, which extends the Shape class


class Circle extends Shape {
private double radius; // Private variable to store the radius of the circle

Dept. of CSE(DS), Vemana IT 20


OOPS with Java Laboratory 2024-25

// Constructor to initialize the radius


public Circle(double radius) {
// Validate that the radius is positive
if (radius <= 0) {
throw new IllegalArgumentException("Radius must be positive");
}
this.radius = radius;
}

// Override method to calculate the area of the circle


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

// Override method to calculate the perimeter (circumference) of the circle


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

// Class representing a Triangle, which also extends the Shape class


class Triangle extends Shape {
private double side1; // Side 1 of the triangle
private double side2; // Side 2 of the triangle
private double side3; // Side 3 of the triangle

// Constructor to initialize the sides of the triangle


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

Dept. of CSE(DS), Vemana IT 21


OOPS with Java Laboratory 2024-25

// Validate that all sides are positive


if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
throw new IllegalArgumentException("Sides must be positive");
}
// Validate that the sides can form a triangle using the triangle inequality theorem
if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1) {
throw new IllegalArgumentException("The given sides do not form a triangle");
}
this.side1 = side1; // Assigning values to sides
this.side2 = side2;
this.side3 = side3;
}

// Override method to calculate the area of the triangle using Heron's formula
@Override
public double calculateArea() {
double s = (side1 + side2 + side3) / 2; // Semi-perimeter

return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));


}

// Override method to calculate the perimeter of the triangle


@Override
public double calculatePerimeter() {
return side1 + side2 + side3; // Perimeter = a + b + c
}
}

// Main class to demonstrate the functionality of the Shape subclasses


public class ShapeDemo {
public static void main(String[] args) {

Dept. of CSE(DS), Vemana IT 22


OOPS with Java Laboratory 2024-25

// Creating a Circle object with a radius of 5.0


Circle circle = new Circle(5.0);

// Creating a Triangle object with sides 3.0, 4.0, and 5.0


Triangle triangle = new Triangle(3.0, 4.0, 5.0);

// Calculating and displaying the area and perimeter of the circle


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

// Calculating and displaying the area and perimeter of the triangle


System.out.println("\nTriangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}
Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793

Triangle Area: 6.0


Triangle Perimeter: 12.0

Dept. of CSE(DS), Vemana IT 23


OOPS with Java Laboratory 2024-25

Program 07
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;

Dept. of CSE(DS), Vemana IT 24


OOPS with Java Laboratory 2024-25

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

// 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);

Dept. of CSE(DS), Vemana IT 25


OOPS with Java Laboratory 2024-25

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}
Output
Original Rectangle Info:
Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 8

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8

Program 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 {

Dept. of CSE(DS), Vemana IT 26


OOPS with Java Laboratory 2024-25

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

Program 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!");
}

Dept. of CSE(DS), Vemana IT 27


OOPS with Java Laboratory 2024-25

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");
}
}
}
Output:
Exception caught: Cannot divide by zero!
Finally block executed

Program 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!");
}

Dept. of CSE(DS), Vemana IT 28


OOPS with Java Laboratory 2024-25

// New utility method


public static int addNumbers(int a, int b) {
return a + b;
}
}
// Main program outside the mypack folder
import mypack.MyPackageClass;
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);
}
}

Output:
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8

Program 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 {

Dept. of CSE(DS), Vemana IT 29


OOPS with Java Laboratory 2024-25

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();

Dept. of CSE(DS), Vemana IT 30


OOPS with Java Laboratory 2024-25

// 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();
}
}
Output
Thread ID: 24 is running.

Dept. of CSE(DS), Vemana IT 31


OOPS with Java Laboratory 2024-25

Thread ID: 21 is running.


Thread ID: 23 is running.
Thread ID: 25 is running.
Thread ID: 22 is running.

Program 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 {

Dept. of CSE(DS), Vemana IT 32


OOPS with Java Laboratory 2024-25

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++) {
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.");
}
}
}
}
Output
main Thread Count: 1
Child Thread Count: 1
Child Thread Count: 2
main Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
Child Thread Count: 4
main Thread Count: 4
Child Thread Count: 5
main Thread Count: 5

Dept. of CSE(DS), Vemana IT 33

You might also like