Java Lab Manual (Oops With Java)
Java Lab Manual (Oops With Java)
import java.util.Scanner;
Program 02: Stack Operations: A Stack is a linear data structure that adds and removes
items from the top in a last-in, first-out (LIFO) order.
Output:
Stack Menu:
1. Push : adding the elements
2. Pop: removing the elements
3. Peek :without removing it retrieve to the top on stack
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 1
Enter the value to push: 10
Pushed: 10
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 1
Enter the value to push: 20
Pushed: 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 3
Peeked: 20
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
5. Check if the stack is empty
6. Check if the stack is full
0. Exit
Enter your choice: 4
Stack Contents: 10
Java Code:
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) {
if (percent > 0) {
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
System.out.println(name + "'s salary raised by " + percent + "%. New salary: $" +
salary);
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}
public String toString() {
return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}
public static void main(String[] args) {
// Creating an Employee object
Employee employee = new Employee(1, "John Doe", 50000.0);
Output:
Initial Employee Details:
Employee ID: 1, Name: John Doe, Salary: $50000.0
John Doe's salary raised by 10.0%. New salary: $55000.0
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());
}
}
This TestMyPoint program creates two MyPoint objects, sets and retrieves coordinates, and
tests the various distance calculation methods. Feel free to modify and expand this code as
needed.
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
Output:
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
Java Code:
// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
// Rectangle class implementing Resizable interface
class Rectangle implements Resizable {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// Implementation of Resizable interface
@Override
public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
Output:
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
} }
public class OuterInnerDemo {
public static void main(String[] args) {
// Create an instance of the Outer class
Outer outer = new Outer();
// Call the display method of the Outer class
outer.display();
// Create an instance of the Inner class (nested inside Outer)
Outer.Inner inner = outer.new Inner();
// Call the display method of the Inner class
inner.display();
} }
In this program, the Outer class has a method named display, and it also contains an inner class named
Inner with its own display method. In the main method of the OuterInnerDemo class, an instance of the
outer class (Outer) is created, and its display method is called. Then, an instance of the inner class (Inner)
is created using the outer class instance, and its display method is called. This demonstrates the concept of
nesting classes in Java.
Output:
Java Code
// Custom exception class
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
// Method to perform division and throw custom exception if denominator is zero
static double divide(int numerator, int denominator) throws DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Cannot divide by zero!");
}
return (double) numerator / denominator;
}
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
}
finally {
System.out.println("Finally block executed");
}
}
}
In this program:
The DivisionByZeroException class is a custom exception that extends the Exception class.
The divide method performs division and throws the custom exception if the denominator is zero.
In the main method, we attempt to divide and catch the custom exception if it occurs. The finally block is
used for code that must be executed, whether an exception is thrown or not.
When you run this program with a denominator of 0, it will throw the DivisionByZeroException, catch it,
print the error message, and then execute the finally block.
Output:
Exception caught: Cannot divide by zero!
Finally block executed
Program 10: Packages
Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Java Code:
Package mypack
// Inside a folder named 'mypack'
package mypack;
public class MyPackageClass {
public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}
// New utility method
public static int addNumbers(int a, int b) {
return a + b;
}
}
Now, let’s create the main program in a different file outside the mypack folder:
PackageDemo class using mypack Package
// Main program outside the mypack folder
import mypack.MyPackageClass;
//import mypack.*;
public class PackageDemo {
public static void main(String[] args) {
// Creating an instance of MyPackageClass from the mypack package
MyPackageClass myPackageObject = new MyPackageClass();
// Calling the displayMessage method from MyPackageClass
myPackageObject.displayMessage();
// Using the utility method addNumbers from MyPackageClass
int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);
}
}
To compile and run this program, you need to follow these steps:
Output:
Java Code
class MyRunnable implements Runnable {
private volatile boolean running = true;
@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
}
catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
public void stopThread() {
running = false;
}
}
public class RunnableThreadExample {
public static void main(String[] args) {
// Create five instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();
// 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();
}
}
In this program, we define a MyRunnable class that implements the Runnable interface. The
run method contains a loop where the thread sleeps for 500 milliseconds, printing its ID during
each iteration. We also handle potential interruptions caused by thread operations.
In the RunnableThreadExample class, we create five instances of MyRunnable, each associated
with a separate thread. The start method is called on each thread, initiating their concurrent
execution. After a brief period of allowing the threads to run, we gracefully stop each thread
using the stopThread method.
Output:
Java Code
super(name);
// The run method that will be executed when the thread starts
@Override
try {
} catch (InterruptedException e) {
// Main thread
for (int i = 1; i <= 5; i++) {
try {
} catch (InterruptedException e) {
The constructor of MyThread calls the base class constructor using super(name) to set the thread’s
name and starts the thread.
The run method is overridden and contains a loop to print counts. The thread sleeps for 500
milliseconds in each iteration.
In the main method, an instance of MyThread is created, which starts the child thread
concurrently.
The main thread also prints counts and sleeps for 500 milliseconds in each iteration.
When you run this program, you’ll observe that both the main thread and the child thread are
executed concurrently, and their outputs may be interleaved.
Output: