0% found this document useful (0 votes)
9 views

Java Programs 7 to 12

Uploaded by

shreyase991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Programs 7 to 12

Uploaded by

shreyase991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

$ java ShapeDemo

Circle Area: 78.53981633974483


Circle Perimeter: 31.41592653589793

Triangle Area: 6.0


Triangle Perimeter: 12.0

Program 07 : Resizable interface

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.

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

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

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}
In this program, the Resizable interface declares the methods
resizeWidth and resizeHeight. The Rectangle class implements
this interface and provides the specific implementation for resizing the
width and height. The main method in the ResizeDemo class creates a
Rectangle object, displays its original information, resizes it, and then
displays the updated information.

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

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8

Program 08 : Outer class

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.

Java Code
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 OuterInnerDemo
Outer class display method
Inner class display method

Program 09 : Custom Exception

Develop a JAVA program to raise a custom exception (user defined


exception) for DivisionByZero using try, catch, throw and finally.

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 DivisionByZeroExceptio
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

$ java CustomExceptionDemo
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:
Organize your directory structure as follows:
project-directory/
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
Compile the files:

javac mypack/MyPackageClass.java
javac PackageDemo.java

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

Program 11 : Runnable Interface

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

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() + "
} 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 RunnableThreadExample
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.

Program 12 : Thread Class


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.

Java Code

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

public class ThreadConcurrentExample {


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

// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count: " +
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interru
}
}
}
}
In this program:
The MyThread class extends Thread.
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

$ java ThreadConcurrentExample
main Thread Count: 1

You might also like