0% found this document useful (0 votes)
2 views36 pages

JAVA Lab Manual -B Section

The document is a lab manual for the Object Oriented Programming with JAVA course at Visvesvaraya Technological University. It outlines course objectives, outcomes, and practical components, including various programming tasks such as matrix addition, stack operations, and employee management. Additionally, it covers fundamental concepts of Object-Oriented Programming and the Java Virtual Machine.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

JAVA Lab Manual -B Section

The document is a lab manual for the Object Oriented Programming with JAVA course at Visvesvaraya Technological University. It outlines course objectives, outcomes, and practical components, including various programming tasks such as matrix addition, stack operations, and employee management. Additionally, it covers fundamental concepts of Object-Oriented Programming and the Java Virtual Machine.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

BELAGAVI-590018

DEPARTMENT OF CSE
(Artificial Intelligence and Machine Learning)

JSS ACADEMY OF TECHNICAL EDUCATION


BENGALURU-560060

Lab Manual for Third Semester


Object Oriented Programming with JAVA
BCS306A
Faculty In-charge

Dr. Jayasimha S R

USN

NAME

ACADEMIC YEAR 2024 – 2025


(ODD Semester)
Course objectives:

This course will enable students to,

● 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 (Course Skill Set):

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

1. Demonstrate proficiency in writing simple programs involving branching and looping


structures.

2. Design a class involving data members and methods for the given scenario.

3. Apply the concepts of inheritance and interfaces in solving real world problems.

4. Use the concept of packages and exception handling in solving complex problem

5. Apply concepts of multithreading, autoboxing and enumerations in program


developmentDepartment of CSE(AI&ML)

VISION
 To emerge as center of academic and research excellence by producing graduates to lead the
Artificial Intelligence-driven technological revolution.

MISSION
 Impart quality education in Artificial Intelligence & Machine Learning through state-of-the-art
learning environment.
 To build a vibrant community of faculty and students equipped with interdisciplinary Artificial
Intelligence & Machine Learning knowledge and skills to solve real industry specific problems.
 To facilitate socially responsive research and innovation center to serve the needs of society.
PRACTICAL COMPONENT OF IPCC

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 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
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.
Introduction to Object Oriented Programming with JAVA:

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time

Pre-requisites:
Let us discuss prerequisites by polishing concepts of method declaration and message
passing. Starting with the method declaration consists of six components:
1. Access Modifier: Defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there are 4 types of access specifiers:

 public: Accessible in all classes in your application.


 protected: Accessible within the package in which it is defined and in its subclass(es)
(including subclasses declared outside the package).
 private: Accessible only within the class in which it is defined.
 default (declared/defined without using any modifier): Accessible within the same
class and package within which its class is defined.
2. The return type: The data type of the value returned by the method or void if it does not
return a value.
3. Method Name: The rules for field names apply to method names as well, but the
convention is a little different.
4. Parameter list: Comma-separated list of the input parameters that are defined, preceded by
their data type, within the enclosed parentheses. If there are no parameters, you must use
empty parentheses ().
5. Exception list: The exceptions you expect the method to throw. You can specify these
exception(s).
6. Method body: It is the block of code, enclosed between braces, that you need to execute to
perform your intended operations.
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls
the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and expect it to run on any other Java-enabled system without any
adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM.

The Class loader reads the “.class” file, generate the corresponding binary data and save it in the
method area. For each “.class” file, JVM stores the following information in the method area.
 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. These Class
object can be used by the programmer for getting class level information like the name of the class,
parent name, methods and variable information etc. To get this object reference we can
use getClass() method of Object class.
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; //Scanner class is used to get user input, and it is found in the java.util package.

public class MatrixAddition2

public static void main(String[] args)

int p, q, m, n;

Scanner s = new Scanner(System.in); //read from the standard input stream of the program

System.out.print("Enter number of rows in first matrix:");

p = s.nextInt();

System.out.print("Enter number of columns in first matrix:");

q = s.nextInt();

System.out.print("Enter number of rows in second matrix:");

m = s.nextInt();

System.out.print("Enter number of columns in second matrix:");

n = s.nextInt();

if (p == m && q == n)

int a[][] = new int[p][q];

int b[][] = new int[m][n];

int c[][] = new int[m][n];

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


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

for (int j = 0; j < q; j++)

a[i][j] = s.nextInt();

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

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

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

b[i][j] = s.nextInt();

System.out.println("First Matrix:");

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

for (int j = 0; j < q; j++)

System.out.print(a[i][j]+" ");

System.out.println("");

System.out.println("Second Matrix:");
for (int i = 0; i < m; i++)

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

System.out.print(b[i][j]+" ");

System.out.println("");

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

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

for (int k = 0; k < q; k++)

c[i][j] = a[i][j] + b[i][j];

System.out.println("Matrix after addition:");

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

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

System.out.print(c[i][j]+" ");

}
System.out.println("");

else

System.out.println("Addition would not be possible");

OUTPUT:

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) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] result = new int[n][n];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

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


for (int j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

System.out.println("Resultant Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT:
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 StackOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of values (n): ");
int n = scanner.nextInt();
int[] stack = new int[n];
int top = -1;

while (true) {
System.out.println("\nStack Operations:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
if (top < n - 1) {
System.out.println("Enter value to push: ");
int value = scanner.nextInt();
stack[++top] = value;
} else {
System.out.println("Stack is full. Can't push value.");
}
break;
case 2:
if (top >= 0) {
System.out.println("Popped value: " + stack[top--]);
} else {
System.out.println("Stack is empty. Can't pop value.");
}
break;
case 3:
if (top >= 0) {
System.out.println("Stack content: ");
for (int i = top; i >= 0; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}

OUTPUT:
Enter the number of values (n):
10

Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
1
Enter value to push:
10

Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
1
Enter value to push:
20

Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
Stack content:
20 10

Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
2
Popped value: 20
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
Stack content:
10

Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
4
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 Employee {


private int id;
private String name;
private double salary;

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


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


salary += (salary * (percent / 100));
}

public void displayDetails() {


System.out.println("Employee ID: " + id);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter Employee ID: ");


int id = scanner.nextInt();

System.out.println("Enter Employee Name: ");


String name = scanner.next();

System.out.println("Enter Employee Salary: ");


double salary = scanner.nextDouble();

Employee employee = new Employee(id, name, salary);

System.out.println("Employee Details Before Raise: ");


employee.displayDetails();

System.out.println("Enter percentage to raise salary: ");


double percent = scanner.nextDouble();
employee.raiseSalary(percent);

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


employee.displayDetails();
}
}

OUTPUT:
Enter Employee ID:
722
Enter Employee Name:
arun
Enter Employee Salary:
200000
Employee Details Before Raise:
Employee ID: 722
Name: arun
Salary: 200000.0
Enter percentage to raise salary:
50
Employee Details After Raise:
Employee ID: 722
Name: arun
Salary: 300000.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.

Note:this program contains 2 main JAVA (.java) classes in the terminal compile MyPoint.java first and
compile TestMyPoint.java then run TestMyPoint.java to get the OUTPUT

This TestMyPoint program creates two MyPoint objects, sets and retrieves coordinates, and tests the various
distance calculation methods.
Java Code
MyPoint.java

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

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

TestMyPoint.java

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

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:

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

import java.util.Scanner;
// Shape class (Parent)
class Shape {
void draw() {
System.out.println("Drawing a shape");
}

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

// Circle class (Child)


class Circle extends Shape {
private double radius;

Circle(double radius) {
this.radius = radius;
}

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

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

// Triangle class (Child)


class Triangle extends Shape {
private double base;
private double height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

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

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

// Square class (Child)


class Square extends Shape {
private double side;

Square(double side) {
this.side = side;
}

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

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

public class main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Select a shape (1-3):");
System.out.println("1. Circle");
System.out.println("2. Triangle");
System.out.println("3. Square");
int choice = scanner.nextInt();

Shape shape = null;

switch (choice) {
case 1:
System.out.print("Enter circle radius: ");
double radius = scanner.nextDouble();
shape = new Circle(radius);
break;
case 2:
System.out.print("Enter triangle base: ");
double base = scanner.nextDouble();
System.out.print("Enter triangle height: ");
double height = scanner.nextDouble();
shape = new Triangle(base, height);
break;
case 3:
System.out.print("Enter square side: ");
double side = scanner.nextDouble();
shape = new Square(side);
break;
default:
System.out.println("Invalid choice");
}

if (shape != null) {
shape.draw();
shape.erase();
}
}
}

OUTPUT:

Select a shape (1-3):


1. Circle
2. Triangle
3. Square
1
Enter circle radius: 2.3
Drawing a circle with radius 2.3
Erasing a circle with radius 2.3

Select a shape (1-3):


1. Circle
2. Triangle
3. Square
2
Enter triangle base: 5.3
Enter triangle height: 2.3
Drawing a triangle with base 5.3 and height 2.3
Erasing a triangle with base 5.3 and height 2.3
Select a shape (1-3):
1. Circle
2. Triangle
3. Square
3
Enter square side: 5.2
3Drawing a square with side 5.2
Erasing a square with side 5.2
________________________________________________________________________________
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 implementthe respective methods to calculate the area and perimeter of
each shape.
________________________________________________________________________________

import java.util.Scanner;

// Abstract class Shape


abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}

// Circle subclass
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

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

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

// Triangle subclass
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() {
// Calculate semi-perimeter
double s = (side1 + side2 + side3) / 2;
// Use Heron's formula
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

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

public class Main {


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

System.out.println("Choose a shape:");
System.out.println("1. Circle");
System.out.println("2. Triangle");

int choice = scanner.nextInt();

Shape shape = null;

switch (choice) {
case 1:
System.out.print("Enter circle radius: ");
double radius = scanner.nextDouble();
shape = new Circle(radius);
break;
case 2:
System.out.print("Enter side 1: ");
double side1 = scanner.nextDouble();
System.out.print("Enter side 2: ");
double side2 = scanner.nextDouble();
System.out.print("Enter side 3: ");
double side3 = scanner.nextDouble();
shape = new Triangle(side1, side2, side3);
break;
default:
System.out.println("Invalid choice");
System.exit(1);
}

System.out.println("Area: " + shape.calculateArea());


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

OUTPUT:

Choose a shape:
1. Circle
2. Triangle
1
Enter circle radius: 2.0
Area: 12.566370614359172
Perimeter: 12.566370614359172

Choose a shape:
1. Circle
2. Triangle
2
Enter side 1: 2.0
Enter side 2: 3.0
Enter side 3: 3.0
Area: 2.8284271247461903
Perimeter: 8.0
Choose a shape:
1. Circle
2. Triangle
1
Enter circle radius: 2.0
Area: 12.566370614359172
Perimeter: 12.566370614359172

________________________________________________________________________________
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
________________________________________________________________________________
import java.util.Scanner;

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

// Rectangle class implementing Resizable


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

public int calculateArea() {


return width * height;
}

public int calculatePerimeter() {


return 2 * (width + height);
}
}

public class Main {


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

System.out.print("Enter initial rectangle width: ");


int width = scanner.nextInt();

System.out.print("Enter initial rectangle height: ");


int height = scanner.nextInt();

Rectangle rectangle = new Rectangle(width, height);

System.out.println("Initial Rectangle Dimensions:");


System.out.println("Width: " + rectangle.getWidth());
System.out.println("Height: " + rectangle.getHeight());
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());

System.out.print("Do you want to resize? (yes/no): ");


scanner.nextLine(); // Consume newline left-over
String choice = scanner.nextLine().toLowerCase();

while (choice.equals("yes")) {
System.out.println("Choose resize option:");
System.out.println("1. Resize width");
System.out.println("2. Resize height");
System.out.println("3. Resize both");

int resizeChoice = scanner.nextInt();


switch (resizeChoice) {
case 1:
System.out.print("Enter new width: ");
int newWidth = scanner.nextInt();
rectangle.resizeWidth(newWidth);
break;
case 2:
System.out.print("Enter new height: ");
int newHeight = scanner.nextInt();
rectangle.resizeHeight(newHeight);
break;
case 3:
System.out.print("Enter new width: ");
newWidth = scanner.nextInt();
System.out.print("Enter new height: ");
newHeight = scanner.nextInt();
rectangle.resizeWidth(newWidth);
rectangle.resizeHeight(newHeight);
break;
default:
System.out.println("Invalid choice");
}

System.out.println("Updated Rectangle Dimensions:");


System.out.println("Width: " + rectangle.getWidth());
System.out.println("Height: " + rectangle.getHeight());
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());

System.out.print("Do you want to resize again? (yes/no): ");


scanner.nextLine(); // Consume newline left-over
choice = scanner.nextLine().toLowerCase();
}
}
}

OUTPUT:

Enter initial rectangle width: 5


Enter initial rectangle height: 6
Initial Rectangle Dimensions:
Width: 5
Height: 6
Area: 30
Perimeter: 22
Do you want to resize? (yes/no): yes
Choose resize option:
1. Resize width
2. Resize height
3. Resize both
1
Enter new width: 3
Updated Rectangle Dimensions:
Width: 3
Height: 6
Area: 18
Perimeter: 18
Do you want to resize again? (yes/no):
________________________________________________________________________________
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.
________________________________________________________________________________
Concepts Used in this program is Constructor, this keyword, Nested Class
// Outer class
class Outer {
private int num1;
private int num2;

// Constructor
public Outer(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}

// Outer class display method


public void display() {
System.out.println("Outer class display method:");
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
}

// Inner class
public class Inner {
// Inner class display method
public void display() {
int result = num1 + num2;
System.out.println("Inner class display method:");
System.out.println("Result: " + result);
}
}
}

// Main class
public class Main {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);

// Prompt user for two numbers


System.out.print("Enter first number: ");
int num1 = scanner.nextInt();

System.out.print("Enter second number: ");


int num2 = scanner.nextInt();

// Create Outer object


Outer outer = new Outer(num1, num2);

// Call outer class display method


outer.display();

// Create Inner object


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

// Call inner class display method


inner.display();
}
}

OUTPUT:

Enter first number: 20


Enter second number: 30
Outer class display method:
Number 1: 20
Number 2: 30
Inner class display method:
Result: 50
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 DivisionByZero extends Exception {
public DivisionByZero(String message) {
super(message);
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
int dividend = 10;
int divisor = 0;

try {
if (divisor == 0) {
throw new DivisionByZero("Cannot divide by zero!");
}
int quotient = divide(dividend, divisor);
System.out.println("Quotient: " + quotient);
} catch (DivisionByZero e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}

public static int divide(int dividend, int divisor) {


return dividend / divisor;
}
}

Output:

Caught Exception: 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.

Step 1: Create a package mypack

Create a new directory mypack in your project directory.

Step 2: Create classes within mypack package

mypack/MyClass.java:

package mypack;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass!");
}
}

mypack/MyInterface.java:
java
package mypack;

public interface MyInterface {


void print();
}

`mypack/MySubClass.java`:

package mypack;

public class MySubClass implements MyInterface {


@Override
public void print() {
System.out.println("Hello from MySubClass!");
}
}

*Step 3: Create a class to import and implement `mypack`*

`MainClass.java`:

import mypack.*;

public class MainClass {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
obj1.display();

MySubClass obj2 = new MySubClass();


obj2.print();
}
}

*Alternative Import Statement:*

Instead of importing all classes using `import mypack.*;`, you can import specific classes:

import mypack.MyClass;
import mypack.MySubClass;

*Compilation and Execution:*

Compile the classes:

javac mypack/MyClass.java mypack/MyInterface.java mypack/MySubClass.java MainClass.java

Run the `MainClass`:

java MainClass

Output:

Hello from MyClass!


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

class MyRunnable implements Runnable {


private String threadName;

public MyRunnable(String threadName) {


this.threadName = threadName;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " is running. Iteration: " + i);
try {
Thread.sleep(500); // Suspend thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(threadName + " is interrupted.");
}
}
}
}

public class ThreadCreationUsingRunnable {


public static void main(String[] args) {
// Create Runnable instances
MyRunnable runnable1 = new MyRunnable("Thread-1");
MyRunnable runnable2 = new MyRunnable("Thread-2");
MyRunnable runnable3 = new MyRunnable("Thread-3");

// Create threads
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
Thread thread3 = new Thread(runnable3);

// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
``

Output:

Thread-1 is running. Iteration: 0


Thread-2 is running. Iteration: 0
Thread-3 is running. Iteration: 0
Thread-1 is running. Iteration: 1
Thread-2 is running. Iteration: 1
Thread-3 is running. Iteration: 1
Thread-1 is running. Iteration: 2
Thread-2 is running. Iteration: 2
Thread-3 is running. Iteration: 2
Thread-1 is running. Iteration: 3
Thread-2 is running. Iteration: 3
Thread-3 is running. Iteration: 3
Thread-1 is running. Iteration: 4
Thread-2 is running. Iteration: 4
Thread-3 is running. Iteration: 4
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.

// MyThread class extending Thread


class MyThread extends Thread {
private String threadName;

// Constructor calling base class constructor using super


public MyThread(String threadName) {
super(threadName); // Call base class constructor
this.threadName = threadName;
}

// Override run method


@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " is running. Iteration: " + i);
try {
Thread.sleep(500); // Suspend thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(threadName + " is interrupted.");
}
}
}
}

public class ThreadCreation {


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

// Start child thread


childThread.start();

// Main thread execution


for (int i = 0; i < 5; i++) {
System.out.println("Main Thread is running. Iteration: " + i);
try {
Thread.sleep(500); // Suspend main thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Main Thread is interrupted.");
}
}
}
}
``

Output:

Main Thread is running. Iteration: 0


Child Thread is running. Iteration: 0
Main Thread is running. Iteration: 1
Child Thread is running. Iteration: 1
Main Thread is running. Iteration: 2
Child Thread is running. Iteration: 2
Main Thread is running. Iteration: 3
Child Thread is running. Iteration: 3
Main Thread is running. Iteration: 4
Child Thread is running. Iteration: 4

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