JAVA MANUAL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

CMR INSTITUTE OF TECHNOLOGY


Department of Artificial Intelligence and DataScience

LAB MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY


(BCS306A)
Semester-III

Academic Year: 2023-2024

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

Syllabus
Part-A-
List of problems for which student should develop program and execute in the
Laboratory
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

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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).

Algorithm:
1. Begin
2. Display message: "Enter the order N of the matrices."
3. Read N from the user. //Initially keep N<5 for comfort
4. Create two matrices (matrix1 and matrix2) of size N x N.
a. Read elements of the first matrix.
b. Read elements of the second matrix.
5. For all row elements (RowElement 1 to N)
6. For all column elements (Column Element 1 to N)
a. sumMatrix[RowElement, ColumnElement] = Matrix1[RowElement, ColumnElement]+
Matrix2[RowElement, ColumnElement].
7. Display "Sum matrix”
8. End

Program

//This program reads 2 n*n matrices, adds them and displays the sum.

//Date and Time:19-12-2023 at 10Am

//Author:Anushree

//Package defined

package lab2;

import java.util.Scanner;

public class MatrixAddition {


int orderOfMatrix;

public static void main(String[] args) {


Scanner my_scanner = new Scanner(System.in);
System.out.print("Enter the order N of the matrices: ");

// Remove the declaration of local variable orderOfMatrix


int orderOfMatrix = my_scanner.nextInt();

MatrixAddition matrixAddition = new MatrixAddition();


Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
matrixAddition.orderOfMatrix = orderOfMatrix;

int[][] matrix1 = new int[orderOfMatrix][orderOfMatrix];


int[][] matrix2 = new int[orderOfMatrix][orderOfMatrix];

// Reading the two matrices


System.out.println("Enter elements of the first matrix:");
matrixAddition.fillMatrix(matrix1, my_scanner);

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


matrixAddition.fillMatrix(matrix2, my_scanner);

// Addition of two matrices


int[][] sumMatrix = matrixAddition.addMatrices(matrix1, matrix2);

System.out.println("Resultant matrix after addition:");


matrixAddition.printMatrix(sumMatrix);

my_scanner.close();
}

// Method to read a matrix with user input


private void fillMatrix(int[][] matrix, Scanner my_scanner) {
for (int row = 0; row < orderOfMatrix; row++) {
for (int col = 0; col < orderOfMatrix; col++) {
System.out.print("Enter element at pos ("+(row+1) + "," +(col+1) + "):");
matrix[row][col] = my_scanner.nextInt();
}
}
}

// Method to add two matrices


private int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int[][] sumMatrix = new int[orderOfMatrix][orderOfMatrix];

for (int row = 0; row < orderOfMatrix; row++) {


for (int col = 0; col < orderOfMatrix; col++) {
sumMatrix[row][col] = matrix1[row][col] + matrix2[row][col];
}
}

return sumMatrix;
}

// Method to print a matrix


private void printMatrix(int[][] matrix) {
for (int row = 0; row < orderOfMatrix; row++) {
for (int col = 0; col < orderOfMatrix; col++) {
System.out.print(matrix[row][col] + " ");
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
}
System.out.println(); // Print a new line after each row
}
}
}
Extra Challenge:

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

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.

Algorithm:
1. Initialize the LimitedStack:
Create a LimitedStack object with a maximum size of 10.
2. Display Menu and Get User Choice:
Display a menu with options for push, pop, peek, check if empty, check if full, and exit.
3. Use a loop to repeatedly ask the user for their choice until they choose to exit.
Perform Operations Based on User Choice:
If the user chooses:
• Push (1): Ask the user for a value and push it onto the stack.
• Pop (2): Pop an element from the stack.
• Peek (3): Display the top element of the stack.
• Check if Empty (4): Display whether the stack is empty.
• Check if Full (5): Display whether the stack is full.
• Exit (0): Exit the program.
4. Repeat the process until the user chooses to exit.
5. Close Scanner:
Close the Scanner used for user input.

Algorithm for push operation


Begin
if stack is full
return
endif
else
increment top
stack[top] assign value end
else
end procedure

Algorithm for pop operation


Begin
if stack is empty
return
endif
else
store value of stack[top]
decrement top
return value
end else
end procedure

Algorithm for peak operation


begin
return stack[top]
end procedure

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Algorithm for isfull()
begin
if stack length is equal to the maximum stack size
return true
endif
else
return false
end else end procedure

Algorithm for isempty()


begin
if top < 1
return true
else
return false
end procedure

Program

//This program is about showing the different operations of Stack

//Date and Time:19-12-2023 at 10Am

//Author:Anushree

//Package

package practice;
import java.util.Scanner;

public class LimitedStack {


private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;

public LimitedStack() {
stackArray = new int[MAX_SIZE];
top = -1;
}

public void push(int value_Push) {


if (top < MAX_SIZE - 1) {
stackArray[++top] = value_Push;
System.out.println("Pushed: " + value_Push);
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
} else {
System.out.println("Stack is full. Cannot push " + value_Push);
}
}

public int pop() {


if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // You can choose another value to indicate an empty stack
}
}

public int peek() {


if (top >= 0) {
System.out.println("Top element: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. No top element.");
return -1; // You can choose another value to indicate an empty stack
}
}

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == MAX_SIZE - 1;
}

public static void main(String[] args) {


LimitedStack stack = new LimitedStack();
Scanner m_scanner = new Scanner(System.in);

int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Check if empty");
System.out.println("5. Check if full");
System.out.println("0. Exit");

System.out.print("Enter your choice: ");


Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
choice = my_scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter value to push: ");
int valueToPush = my_scanner.nextInt();
stack.push(valueToPush);
break;

case 2:
stack.pop();
break;

case 3:
stack.peek();
break;

case 4:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;

case 5:
System.out.println("Is the stack full? " + stack.isFull());
break;

case 0:
System.out.println("Exiting program. Bye!");
break;

default:
System.out.println("Invalid choice. Please enter a valid option.");
}

} while (choice != 0);

My_scanner.close();
}
}
Extra Challenge
2a) implement a method reverse() that reverses the order of elements in the stack. Demonstrate the usage of this
method in your main program by reversing the elements and displaying the result.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.
Algorithm
1.Begin
2.Create a Class Employee with appropriate attribute, constructor and method.
3.Method Accepts a parameter percent.
If %>0
Calculate the increase amount (increaseAmount) as salary * (percent / 100).
4.Add increaseAmount to salary.
Print a message indicating the salary increase.
5.In Main Method create an instance of the Employee class.
6.Display initial employee details using a Display method.
7.Call the method to increase the salary by a certain percentage.
Display updated employee details using the Display method.
8.End
Program
Package Defined
package practice;
import java.util.*;
import section

public class Employee {


private int employeeId;
private String employee_name; // Updated variable name
private double employee_salary; // Updated variable name

public Employee(int employeeId, String employee_name, double employee_salary) {


this.employeeId = employeeId;
this.employee_name = employee_name;
this.employee_salary = employee_salary;
}

public void raiseSalary(double percent) {


if (percent > 0) {
this.employee_salary += this.employee_salary * (percent / 100);
}
}

public void displayDetails() {


Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
System.out.println("Employee ID: " + this.employeeId);
System.out.println("Name: " + this.employee_name); // Updated variable name
System.out.println("Salary: $" + String.format("%.2f", this.employee_salary));
// Updated variable name
System.out.println();
}

public static void main(String[] args) {


// Creating an employee object
Employee employee1 = new Employee(1, "John Doe", 50000.0);
Scanner my_scanner = new Scanner(System.in);

// Displaying initial details


System.out.println("Initial Employee Details:");
employee1.displayDetails();

System.out.println("Enter what is the raise percentage of employee");


int raisepercentage = my_scanner.nextInt();
employee1.raiseSalary(raisepercentage);

// Displaying updated details


System.out.println("Employee Details After Raise:");
employee1.displayDetails();
}
}

Extra Challenge:

3A)Develop a Java program that defines a class named Employee. The class should include methods to collect details
for two employees, each with an ID, name, and salary. The raiseSalary(percent) method should increase the salary by
the given percentage. Additionally, implement a method to print the details of the employee with the highest salary
increment. Create a suitable main method for demonstration.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.
Algorithm for Mypoint Program
1.Begin
2.Create a Class MyPoint with appropriate and methods
Default Constructor(): Initializes the point at the default location (0, 0).
Overloaded Constructor(x, y): Initializes the point with the given x and y coordinates.
3. Default Constructor()sets x and y to 0.
Overloaded Constructor(x, y) sets x and y to the provided values.
4.setXY(x, y):
Set the x and y coordinates.
5.getXY():
Return an array containing x and y.
6.toString():Return a string in the format "(x, y)".
7.distance(x, y):Calculate and return the distance from this point to the point at the given (x, y) coordinates.
8.distance(another):Calculate and return the distance from this point to another MyPoint instance.
10.distance():
Calculate and return the distance from this point to the origin (0, 0).
11.End

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Algorithm for TestMyPoint Program
1.Begin
2.Create a class TestMyPoint
Create instances of MyPoint.
Test all the methods defined in the MyPoint class.
3.End

Program
package PROJECT;

public class MyPoint {

private int x_coordinates;


private int y_coordinates;
// Default constructor
public MyPoint() {
this.x_coordinates = 0;
this.y_coordinates = 0;
}
// Overloaded constructor
public MyPoint(int x_coordinates, int y_coordinates) {
this.x_coordinates = x_coordinates;
this.y_coordinates = y_coordinates;
}
// Set x and y
public void setXY(int x_point, int y_point) {
this.x_coordinates = x_point;
this.y_coordinates = y_point;
}
// Get x and y as a 2-element int array
public int[] getXY() {
int[] coordinates = { this.x_coordinates, this.y_coordinates };
return coordinates;
}
// Calculate the distance from this point to another point
public double distance(int x_coordinates, int y_coordinates) {

int x_coordinatesDiff = this.x_coordinates - x_coordinates;


int y_coordinatesDiff = this.y_coordinates - y_coordinates;
return Math.sqrt(x_coordinatesDiff * x_coordinatesDiff + y_coordinatesDiff *
y_coordinatesDiff);
}
// Calculate the distance from this point to another MyPoint instance
public double distance(MyPoint another) {
int x_coordinatesDiff = this.x_coordinates - another.x_coordinates;
int y_coordinatesDiff = this.y_coordinates - another.y_coordinates;
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
return Math.sqrt(x_coordinatesDiff * x_coordinatesDiff + y_coordinatesDiff *
y_coordinatesDiff);
}
// Calculate the distance from this point to the origin (0,0)
public double distance() {
return Math.sqrt(this.x_coordinates * this.x_coordinates + this.y_coordinates *
this.y_coordinates);
}
// Override toString() method to provide a string description of the point
@Override
public String toString() {
return "(" + this.x_coordinates + ", " + this.y_coordinates + ")";
}
}

//Class TestMyPoint
package PROJECT;

public class TestMyPoint {

public static void main(String[] args) {


MyPoint point1 = new MyPoint(); // Default constructor (0,0)
MyPoint point2 = new MyPoint(3, 4); // Custom constructor (3,4)
System.out.println("point1: " + point1);
System.out.println("point2: " + point2);
// Set x and y for point1
point1.setXY(1, 2);
System.out.println("point1 after setXY(1, 2): " + point1);
// Get x and y for point2 as an array
int[] coordinates = point2.getXY();
System.out.println("point2 coordinates: (" + coordinates[0] + ", " +
coordinates[1] + ")");
// Calculate the distance between point1 and point2
double distance1 = point1.distance(point2);
System.out.println("Distance between point1 and point2: " + distance1);
// Calculate the distance between point1 and the origin (0,0)
double distance2 = point1.distance();
System.out.println("Distance between point1 and the origin: " + distance2);
}
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Extra Challenge:

4a) Design a Java program that includes a class named MyCircle which represents a circle based on the MyPoint
class. The MyCircle class should have the following features:

Two instance variables: a center (of type MyPoint) representing the center of the circle, and a radius (double)
representing the radius of the circle.

A default constructor that creates a circle with the center at the default location (0, 0) and a default radius.

An overloaded constructor that allows creating a circle with a specific center and radius.

Methods getCenter() and setCenter(MyPoint center) to get and set the center of the circle.

Methods getRadius() and setRadius(double radius) to get and set the radius of the circle.

A method getArea() that returns the area of the circle.

A method getCircumference() that returns the circumference of the circle.

A method distance(MyCircle another) that returns the distance between the centers of two circles.

Develop the code for the class MyCircle and also create a Java program (called TestMyCircle) to test all the
methods defined in the class.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.
Algorithm

1.Begin
2.Create a Class Shape with the methods Draw() and erace()
• draw(): Display a message indicating drawing of a generic shape.
• erase(): Display a message indicating erasing a generic shape.
3. Create a Class Circle that extends Shape with Methods:
• draw(): Display a message indicating drawing a circle.
• erase(): Display a message indicating erasing a circle.
4. Create a Class Triangle that extends Shape with Methods:
• draw(): Display a message indicating drawing a triangle.
• erase(): Display a message indicating erasing a triangle.
5. Create a Class Square that extends Shape with the Methods:
• draw(): Display a message indicating drawing a square.
• erase(): Display a message indicating erasing a square.
6. In a Main Program Create objects of Circle, Triangle, and Square. Demonstrate polymorphism by calling draw()
and erase() methods on each object.
7. End.

Program

package project1;

//Base class Shape


class Shape {
public void draw() {
System.out.println("Drawing a shape");
}

public void erase() {


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

//Subclass Circle
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
}

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

//Subclass Triangle
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}

@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}

//Subclass Square
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}

@Override
public void erase() {
System.out.println("Erasing a square");
}
}
public class Shapes {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

for (Shape shape : shapes) {


shape.draw();
shape.erase();
System.out.println();
}
}
}

Extra Challenge:

Program 5 a) Include an additional subclass named Area that inherits from the Shape class. Implement a unique
method calculate_area() specific to the Area subclass. In your main program, demonstrate how polymorphism allows
you to treat objects of the Area class interchangeably with objects of the other Shape subclasses.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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

Create Class Shape


package Abstract;

public abstract class Shape {

public abstract double calculateArea();


public abstract double calculatePerimeter();
}
Create Class Circle
package Abstract;

public class Circle extends Shape


{
private double radius;

public Circle(double radius)


{
this.radius = radius;
}

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

@Override
public double calculatePerimeter()
{
return 2 * Math.PI * radius;
}
}
Create a Class Triangle
package Abstract;

public class Triangle extends Shape


{
private double side1;

private double side2;


Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
private double side3;

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


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

@Override
public double calculateArea()
{
// 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
public double calculatePerimeter()
{ return side1 + side2 + side3;
}
}

Create a class Test

package Abstract;

public class Test


{

public static void main(String[] args)


{
Circle circle = new Circle(5.0);
// Create a circle and calculate its area and perimeter Circle circle = new Circle(5.0);
System.out.println("Circle - Area: " + circle.calculateArea());
System.out.println("Circle - Perimeter: " + circle.calculatePerimeter());
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
// Create a triangle and calculate its area and perimeter Triangle triangle = new
Triangle(3.0, 4.0, 5.0);
System.out.println("Triangle - Area: " + triangle.calculateArea());

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


}
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Extra Challenge:

6a.Create an abstract class Animal with abstract methods makeSound() and move(). Create two subclasses Dog
and Fish that extend the Animal class and implement the respective methods. In the main method, create instances
of Dog and Fish, call their methods, and display the output.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Program-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.

Create a interface Resizable


package Interface;
//import section
public interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}

Create a class Rectangle


package Interface;

public class Rectangle implements Resizable {


private int width;
private int height;
public Rectangle(int width, int height) { this.width = width;
this.height = height;
}
@Override
public void resizeWidth(int width)
{ this.width = width;
}
@Override
public void resizeHeight(int height) { this.height = height;
}
public int getWidth() { return width;

}
public int getHeight() { return height;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + "]";
}
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Create a class Test
package Interface;

public class Test


{

public static void main(String[] args)


{
Rectangle rectangle = new Rectangle(10, 20);
System.out.println("Original Rectangle: " + rectangle);
// Resize the rectangle rectangle.resizeWidth(30); rectangle.resizeHeight(40);
System.out.println("Resized Rectangle: " + rectangle);
}
}
Extra Challenge:

7A) Design a Java program that simulates a basic online shopping system. Create an interface named Purchasable

with methods calculatePrice() and displayDetails(). Develop a class Product that implements the Purchasable

interface. The Product class should have attributes such as name, price, and quantity. Implement the methods to

calculate the total price based on the quantity and display the product details.

Additionally, create a class named ShoppingCart that can hold a collection of Purchasable items. The ShoppingCart

class should have methods to add items, calculate the total cost of all items in the cart, and display the details of

each item in the cart.

Demonstrate the usage of these classes in a Main class by creating instances of Product, adding them to a

ShoppingCart, and displaying the total cost along with individual product details.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
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.
package project1;

package OUTER_CLASS;
class OuterClass {
void display()
{
System.out.println("This is the outer class display method.");
}

// Inner class
class Inner {
void display()
{
System.out.println("This is the inner class display method.");
}
}
}

// Outinclass.java

public class Outinclass {

public static void main(String[] args) {


OuterClass outer = new OuterClass();
outer.display(); // Calls the outer class display method
OuterClass.Inner inner = outer.new Inner();
// To call the inner class display method, first create an instance of the inner class
OuterClass.Inner inner = outer.new Inner();

inner.display(); // Calls the inner class display method

}
}
Extra Challenge:

Imagine you are designing a Java program to model a multimedia player. Develop a Java program that includes an

outer class named MediaPlayer with a method play. Inside the MediaPlayer class, create an inner class named

AudioPlayer with its own method called playAudio. Both the outer and inner classes should have appropriate

constructors.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
In the main class, instantiate the MediaPlayer class and call both the play method from the outer class and the

playAudio method from the inner class to simulate the playback of audio.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Program-9: Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
package Exception;
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
public class CustomeException {

public static void main(String[] args) {


try {
int numerator = 10;
int denominator = 0;

if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}

int result = numerator / denominator;


System.out.println("Result: " + result);
}
catch (DivisionByZeroException e)
{
System.err.println("Custom Exception: " + e.getMessage());
}
catch (ArithmeticException e)
{
System.err.println("Arithmetic Exception: " + e.getMessage());
}
finally {
System.out.println("This block always gets executed.");
}
}
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Extra Challenge:
Modify the above program to include user input for both numerator and denominator. Implement error handling to
ensure that the user enters valid integers for numerator and denominator. If the user enters invalid input (non-
integer or zero as the denominator), raise the DivisionByZeroException with an appropriate error message.
Handle any other possible exceptions gracefully.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

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

Inside the Java project, create a package named "mypack."


Inside the "mypack" package, create a Java interface called "MyInterface" with a method "displayMessage":
package mypack;

public interface MyInterface


{

void displayMessage(String message);

Create a Java class in the same package that implements the "MyInterface" interface. For example, create a class
named "MyClass" in the "mypack" package:

package mypack;

public class MyClass implements MyInterface {


@Override

public void displayMessage(String message) { System.out.println("Message from

MyClass: " + message);


}

create a separate Java class in your project (not inside the "mypack" package) to use the "mypack" package:

package Testmypack;
import mypack.*;
public class Test {
public static void main(String[] args)
{
MyInterface myInterfaceObj = new MyClass();
myInterfaceObj.displayMessage("Hello from Main class!");
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

Extra Challenge:

10a) Extend the program to include a new method in the MyPackageClass that calculates the factorial of a number.
Import and use this method in the MainClass to calculate the factorial of a number entered by the user. Implement
proper exception handling to handle non-integer input or negative numbers gracefully. Additionally, provide an
option for the user to calculate the factorial multiple times until they choose to exit the program.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

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).
package Thread;

public class RunnableThread {

public static void main(String[] args) {


MyRunnable runnable1 = new MyRunnable("Thread 1");
MyRunnable runnable2 = new MyRunnable("Thread 2");

// Create instances of our Runnable class


MyRunnable runnable1 = new MyRunnable("Thread 1");
MyRunnable runnable2 = new MyRunnable("Thread 2");

// Create threads and start them


Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);

thread1.start();
// Start the first thread
thread2.start(); // Start the second thread
}
}

class MyRunnable implements Runnable {


private String threadName;

public MyRunnable(String name) {


this.threadName = name;
}

@Override
public void run() {
try {
System.out.println(threadName + " is running.");
Thread.sleep(500); // Sleep for 500 milliseconds
System.out.println(threadName + " is done.");
}
catch (InterruptedException e)
{ System.err.println(threadName + " was interrupted.");
}
}
}

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
Extra Challenge:

11a) Extend the program to introduce a third thread (Thread 3) that runs in the background and prints a message
after the other two threads have completed. Implement a mechanism to ensure that the third thread waits for both
Thread 1 and Thread 2 to finish before executing. Use any synchronization technique of your choice.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.


OOPS with Java Laboratory– BCS306A Academic Year: 2023-24

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

package Thread;

public class Threadexample {

public static void main(String[] args)


{
MyThread myThread = new MyThread();
myThread.start(); // Start the child thread

// Main thread
for (int mainThread = 1; mainThread <= 5; mainThread++)
{
System.out.println("Main Thread: " + mainThread);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
System.err.println("Main Thread interrupted");
}
}

System.out.println("Main Thread is done.");


}
}

class MyThread extends Thread { MyThread() {


super(); // Call the base class (Thread) constructor
}

@Override
public void run() {
// Child thread
for (int childThread = 1; childThread <= 5; childThread++)
{
System.out.println("Child Thread: " + childThread);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
System.err.println("Child Thread interrupted");
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
}
}

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


}
}

Extra Challenge:
12a) Extend the program to introduce a third thread (Child Thread 2) that runs concurrently with both the main
thread and the first child thread. Implement a mechanism to ensure that all three threads (Main Thread, Child Thread
1, and Child Thread 2) print their counts in a synchronized manner, such that the output is sequential and not
interleaved.

Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy