Lab Oops

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

BET’S

BASAVAKALYANENGINEERINGCOLLEGE,
BASAVAKALYAN
Approved by AICTE and Affilated toVTU Belagavi
[ISO Certified:9001-2015]
Basavakalyan-585327Dist.Bidar,Karnataka

Oops with Java Laboratory(BCS306A)


III Semester
LAB MANUAL

Prepared by:Pooja Patil

Department of Computer Science and Engineering


Academic Year 2023-2024
Oops with Java Laboratory Manual

Program01:MatrixAddition

Developa JAVA programto add TWO matrices of suitable orderN(The value


of N should be read from command line arguments).

JavaCode
import java.util.Scanner;

public class MatrixAddition {


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

System.out.print("Enter the number of rows for the matrices: ");


int rows = input.nextInt();
System.out.print("Enter the number of columns for the matrices: ");
int columns = input.nextInt();

int[][] matrix1 = new int[rows][columns];


int[][] matrix2 = new int[rows][columns];
int[][] resultMatrix = new int[rows][columns];

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


inputMatrixElements(matrix1, input);

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


inputMatrixElements(matrix2, input);

addMatrices(matrix1, matrix2, resultMatrix);

System.out.println("The sum of the matrices is:");


displayMatrix(resultMatrix);

input.close();
}

public static void inputMatrixElements(int[][] matrix, Scanner input) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element [" + (i+1) + "][" + (j+1) + "]: ");
matrix[i][j] = input.nextInt();
}
}
}

public static void addMatrices(int[][] matrix1, int[][] matrix2, int[][] resultMatrix) {

Dept of CSE BKEC ,Basavakalyan Page1


Oops with Java Laboratory Manual
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

public static void displayMatrix(int[][] matrix) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output

Enter the number of rows for the matrices: 2


Enter the number of columns for the matrices: 2
Enter the elements of the first matrix:
Enter element [1][1]: 1
Enter element [1][2]: 2
Enter element [2][1]: 3
Enter element [2][2]: 4
Enter the elements of the second matrix:
Enter element [1][1]: 2
Enter element [1][2]: 4
Enter element [2][1]: 5
Enter element [2][2]: 6
The sum of the matrices is:
3 6

8 10

Dept of CSE BKEC ,Basavakalyan Page2


Oops with Java Laboratory Manual

Program02:StackOperations

Develop a stack class to hold a maximum of 10 integers with suitable methods.


Develop a JAVA main method to illustrate Stack operations.

JavaCode

package com.jsp;

import java.util.Scanner;

public class Stack {

private static final int MAX_SIZE = 10;


private int[] stackArray;
private int top;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
public void push(int value) {
if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {

Dept of CSE BKEC ,Basavakalyan Page3


Oops with Java Laboratory Manual
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}
public void display() {
if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == MAX_SIZE - 1;
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display Stack Contents");
System.out.println("5. Check if the stack is empty");
System.out.println("6. Check if the stack is full");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();

Dept of CSE BKEC ,Basavakalyan Page4


Oops with Java Laboratory Manual
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 6:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();
}
}

Dept of CSE BKEC ,Basavakalyan Page5


Oops with Java Laboratory Manual

Output
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:4 Stack
is empty.

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:5
Isthe stack empty?true

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Checkifthestackis full
0. Exit
Enter your choice: 6
Isthestackfull?false

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:1
Dept of CSE BKEC ,Basavakalyan Page6
Oops with Java Laboratory Manual
Enterthevaluetopush:10
Pushed: 10

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:1
Enterthevaluetopush:20
Pushed: 20

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enter your choice: 4
StackContents:1020

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:3
Peeked: 20

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:1

Dept of CSE BKEC ,Basavakalyan Page7


Oops with Java Laboratory Manual
Enterthevaluetopush:30
Pushed: 30

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enter your choice: 4
StackContents:102030

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:2
Popped: 30

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enteryourchoice:3
Peeked: 20

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0. Exit
Enter your choice: 4
StackContents:1020

Dept of CSE BKEC ,Basavakalyan Page8


Oops with Java Laboratory Manual

StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackis empty
6. Check ifthestack is full
0.Exit
Enteryourchoice:0
Exitingtheprogram.Goodbye!

Dept of CSE BKEC ,Basavakalyan Page9


Oops with Java Laboratory Manual

Program03:EmployeeClass

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)increasesthesalarybythegivenpercentage.Developthe
Employee class and suitable main method for demonstration.

JavaCode
package com.practice;

public class Employee {


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

// Constructor
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}

// Getter methods
public int getId() {
return id;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}

// Method to raise salary by a given percentage


public void raiseSalary(double percent) {
if (percent > 0) {
salary += salary * (percent / 100);
System.out.println(name + "'s salary has been increased by " + percent + "%.");
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}

Dept of CSE BKEC ,Basavakalyan Page10


Oops with Java Laboratory Manual
// Main method for demonstration
public static void main(String[] args) {
// Create an Employee object
// Employee employee = new Employee(101, "John Doe", 50000.0);
Employee employee = new Employee(101, "John Doe", 50000.0);
// Display initial details
System.out.println("Initial Details:");
displayEmployeeDetails(employee);

// Raise the salary by 10%


employee.raiseSalary(10);

// Display details after the salary raise


System.out.println("\nDetails After Salary Raise:");
displayEmployeeDetails(employee);
}

// Helper method to display employee details


private static void displayEmployeeDetails(Employee employee) {
System.out.println("ID: " + employee.getId());
System.out.println("Name: " + employee.getName());
System.out.println("Salary: $" + employee.getSalary());
}
}

Output

Initial Details:
ID: 101
Name: John Doe
Salary: $50000.0
John Doe's salary has been increased by 10.0%.

Details After Salary Raise:


ID: 101
Name: John Doe
Salary: $55000.0

Dept of CSE BKEC ,Basavakalyan Page11


Oops with Java Laboratory Manual

Program04:2DPointClass

AclasscalledMyPoint, whichmodelsa2Dpoint with xandycoordinates,is


designed as follows:

 Twoinstancevariablesx(int)andy(int).
 Adefault(or“no-arg”)constructorthatconstructapointatthedefault
location of (0, 0).
 Aoverloadedconstructorthatconstructs apointwiththegivenxandy
coordinates.
 AmethodsetXY()tosetbothxand y.
 AmethodgetXY()whichreturnsthexandyina2-elementintarray.
 AtoString()methodthatreturnsastring descriptionoftheinstanceinthe
format “(x, y)”.
 Amethodcalleddistance(intx,inty)that returnsthedistancefromthispoint to
another point at the given (x, y) coordinates
 Anoverloadeddistance(MyPointanother)thatreturnsthedistancefromthis
point to the given MyPoint instance (called another)
 Another overloaded distance() method that returns the distance from this
pointtothe origin(0,0)Developthecode fortheclassMyPoint.Alsodevelopa JAVA
program (called TestMyPoint) to test all the methods defined in the class.

JavaCode

package com.practice;
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;
}

// Method to set both x and y

Dept of CSE BKEC ,Basavakalyan Page12


Oops with Java Laboratory Manual
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}

// Method to return the x and y in a 2-element int array


public int[] getXY() {
return new int[]{x, y};
}

// toString method
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

// Method to calculate distance from this point to another point (x, y)


public double distance(int x, int y) {
int dx = this.x - x;
int dy = this.y - y;
return Math.sqrt(dx * dx + dy * dy);
}

// Overloaded method to calculate distance from this point to another MyPoint instance
public double distance(MyPoint another) {
return distance(another.x, another.y);
}

// Another overloaded method to calculate distance from this point to the origin (0,0)
public double distance() {
return distance(0, 0);
}

// Main method for testing


public static void main(String[] args) {
// Create instances of MyPoint
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);

// Display initial points


System.out.println("Point 1: " + point1.toString());
System.out.println("Point 2: " + point2.toString());

// Set new coordinates for point1


point1.setXY(1, 2);
System.out.println("New coordinates for Point 1: " + point1.toString());

Dept of CSE BKEC ,Basavakalyan Page13


Oops with Java Laboratory Manual
// Display coordinates as an array
int[] coordinates = point2.getXY();
System.out.println("Coordinates of Point 2 as array: [" + coordinates[0] + ", " +
coordinates[1] + "]");

// Calculate and display distances


System.out.println("Distance from Point 1 to (0, 0): " + point1.distance());
System.out.println("Distance from Point 2 to Point 1: " + point2.distance(point1));
System.out.println("Distance from Point 1 to (3, 4): " + point1.distance(3, 4));
}

Output
Point 1: (0, 0)
Point 2: (3, 4)
New coordinates for Point 1: (1, 2)
Coordinates of Point 2 as array: [3, 4]
Distance from Point 1 to (0, 0): 2.23606797749979
Distance from Point 2 to Point 1: 2.8284271247461903
Distance from Point 1 to (3, 4): 2.8284271247461903

Dept of CSE BKEC ,Basavakalyan Page14


Oops with Java Laboratory Manual

Program05:Inheritance&Polymorphism–ShapeClass

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

Java Code
package com.practice;
class Shape {
// Member functions
public void draw() {
System.out.println("Drawing a shape");
}

public void erase() {


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

class Circle extends Shape {


// Override draw method for Circle
@Override
public void draw() {
System.out.println("Drawing a circle");
}

// Override erase method for Circle


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

class Triangle extends Shape {


// Override draw method for Triangle
@Override
public void draw() {
System.out.println("Drawing a triangle");
}

// Override erase method for Triangle


@Override
public void erase() {
Dept of CSE BKEC ,Basavakalyan Page15
Oops with Java Laboratory Manual
System.out.println("Erasing a triangle");
}
}

class Square extends Shape {


// Override draw method for Square
@Override
public void draw() {
System.out.println("Drawing a square");
}

// Override erase method for Square


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

public class ShapeDemo {


public static void main(String[] args) {
// Create an array of Shape objects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

// Demonstrate polymorphism by calling draw and erase methods on each shape


for (Shape shape : shapes) {
shape.draw();
shape.erase();
System.out.println(); // Add a newline for better readability
}
}
}

Dept of CSE BKEC ,Basavakalyan Page16


Oops with Java Laboratory Manual

Output
Drawing a circle
Erasing a circle

Drawing a triangle
Erasing a triangle

Drawing a square
Erasing a square

Dept of CSE BKEC ,Basavakalyan Page17


Oops with Java Laboratory Manual
Program05:Abstract Class
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.

Java Code

package com.prcts;

abstract class Shape {


// Abstract methods
public abstract double calculateArea();
public abstract double calculatePerimeter();
}

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

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Implementation of abstract methods


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

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

//Subclass Triangle
class Triangle extends Shape {
private double side1, side2, side3;

// Constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
Dept of CSE BKEC ,Basavakalyan Page18
Oops with Java Laboratory Manual
}

// Implementation of abstract methods


@Override
public double calculateArea() {
// Heron's formula for 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;
}
}

//Main class for demonstration


public class ShapeDemo {
public static void main(String[] args) {
// Create instances of Circle and Triangle
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);

// Display information about Circle


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

// Display information about Triangle


System.out.println("\nTriangle:");
System.out.println("Area: " + triangle.calculateArea());
System.out.println("Perimeter: " + triangle.calculatePerimeter());
}
}

Output

Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793

Triangle:
Area: 6.0
Perimeter: 12.0

Dept of CSE BKEC ,Basavakalyan Page19


Oops with Java Laboratory Manual

Program07: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.

JavaCode
package com.prcts1;

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

//Class Rectangle implementing Resizable interface


class Rectangle implements Resizable {
private int width;
private int height;

// Constructor
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}

// Getter methods
public int getWidth() {
return width;
}

public int getHeight() {


return height;
}

// Implementation of Resizable interface methods


@Override
public void resizeWidth(int width) {
if (width > 0) {
this.width = width;
System.out.println("Width resized to: " + width);
} else {
System.out.println("Invalid width. Width remains unchanged.");
}
Dept of CSE BKEC ,Basavakalyan Page20
Oops with Java Laboratory Manual
}

@Override
public void resizeHeight(int height) {
if (height > 0) {
this.height = height;
System.out.println("Height resized to: " + height);
} else {
System.out.println("Invalid height. Height remains unchanged.");
}
}
}

//Main class for demonstration


public class ResizableDemo {
public static void main(String[] args) {
// Create an instance of Rectangle
Rectangle rectangle = new Rectangle(10, 5);

// Display initial dimensions


System.out.println("Initial Dimensions:");
displayRectangleDimensions(rectangle);

// Resize width and height


rectangle.resizeWidth(15);
rectangle.resizeHeight(8);

// Display dimensions after resizing


System.out.println("\nDimensions After Resizing:");
displayRectangleDimensions(rectangle);
}

// Helper method to display rectangle dimensions


private static void displayRectangleDimensions(Rectangle rectangle) {
System.out.println("Width: " + rectangle.getWidth());
System.out.println("Height: " + rectangle.getHeight());
}

Dept of CSE BKEC ,Basavakalyan Page21


Oops with Java Laboratory Manual

Output

Initial Dimensions:
Width: 10
Height: 5
Width resized to: 15
Height resized to: 8

Dimensions After Resizing:


Width: 15
Height: 8

Dept of CSE BKEC ,Basavakalyan Page22


Oops with Java Laboratory Manual

Program08:Outerclass

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.

JavaCode

package com.prcts1;

class Outer {
// Outer class display function
void display() {
System.out.println("Outer class display");
}

// Inner class
class Inner {
// Inner class display function
void display() {
System.out.println("Inner class display");
}
}
}

//Main class
public class OuterInnerDemo {
public static void main(String[] args) {
// Create an instance of the outer class
Outer outerObj = new Outer();

// Call the display function of the outer class


outerObj.display();

// Create an instance of the inner class using the outer class instance
Outer.Inner innerObj = outerObj.new Inner();

// Call the display function of the inner class


innerObj.display();
}

Dept of CSE BKEC ,Basavakalyan Page23


Oops with Java Laboratory Manual

Output

Outer class display


Inner class display

Dept of CSE BKEC ,Basavakalyan Page24


Oops with Java Laboratory Manual

Program09:CustomException

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


for DivisionByZero using try, catch, throw and finally.

JavaCode

package com.prcts1;

class DivisionByZeroException extends Exception {


public DivisionByZeroException(String message) {
super(message);
}
}

//Main class
public class CustomExceptionExample {
// Method that performs division and raises the custom exception
public static double performDivision(int numerator, int denominator) throws
DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
return (double) numerator / denominator;
}

public static void main(String[] args) {


try {
// Attempting to perform division
int numerator = 10;
int denominator = 0;

double result = performDivision(numerator, denominator);


System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
// Catching the custom exception
System.err.println("Exception caught: " + e.getMessage());
} finally {
// Code in the finally block will execute whether an exception occurs or not
System.out.println("Finally block executed.");
}
}
}

Dept of CSE BKEC ,Basavakalyan Page25


Oops with Java Laboratory Manual

Output
Exception caught: Division by zero is not allowed.
Finally block executed.

Dept of CSE BKEC ,Basavakalyan Page26


Oops with Java Laboratory Manual

Program10:Packages

Developa JAVA program to create a package named mypack and import&


implement it in a suitable class.

Java Code

package mypack;

public class MyClass {


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

//CREATE NEW PACKAGE


package pack;

import mypack.MyClass;

public class MainClass {


public static void main(String[] args) {
// Creating an object of MyClass from the mypack package
MyClass myObject = new MyClass();

// Calling the displayMessage method from MyClass


myObject.displayMessage();
}
}

OUTPUT

Hello from mypack.MyClass!

Dept of CSE BKEC ,Basavakalyan Page27


Oops with Java Laboratory Manual

Program11: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
package pack;

class MyRunnable implements Runnable {


private String threadName;

// Constructor to set the thread name


public MyRunnable(String name) {
this.threadName = name;
}

// The run method contains the code that will be executed in the new thread
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + ": Count " + i);
Thread.sleep(500); // Suspend the thread for 500 milliseconds
}
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
// Creating instances of MyRunnable and passing thread names
MyRunnable myRunnable1 = new MyRunnable("Thread 1");
MyRunnable myRunnable2 = new MyRunnable("Thread 2");

// Creating threads and assigning runnable objects


Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);

// Starting the threads


thread1.start();
Dept of CSE BKEC ,Basavakalyan Page28
Oops with Java Laboratory Manual
thread2.start();
}}

Output
Thread 2: Count 1
Thread 1: Count 1
Thread 2: Count 2
Thread 1: Count 2
Thread 2: Count 3
Thread 1: Count 3
Thread 2: Count 4
Thread 1: Count 4
Thread 1: Count 5
Thread 2: Count 5

Dept of CSE BKEC ,Basavakalyan Page29


Oops with Java Laboratory Manual

Program12:ThreadClass

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.

JavaCode
package pack;

class MyThread extends Thread {


// Constructor of MyThread class
public MyThread(String name) {
super(name); // Calling the base class constructor using super
start(); // Start the thread
}

// The run method contains the code that will be executed in the new thread
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": Count " + i);
try {
Thread.sleep(500); // Suspend the thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
}
}
}

public class ThreadExample {


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

// Code in the main thread


for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": Count " + i);
try {
Thread.sleep(500); // Suspend the main thread for 500 milliseconds
}

Dept of CSE BKEC ,Basavakalyan Page30


Oops with Java Laboratory Manual
catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
}
}
}

OUTPUT

main: Count 1
Child Thread: Count 1
Child Thread: Count 2
main: Count 2
Child Thread: Count 3
main: Count 3
main: Count 4
Child Thread: Count 4
main: Count 5
Child Thread: Count

Dept of CSE BKEC ,Basavakalyan Page31


Oops with Java Laboratory Manual

Dept of CSE BKEC ,Basavakalyan Page32

You might also like