0% found this document useful (0 votes)
130 views30 pages

JAVA LAB MANUAL - 3rd SEM

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

CAMBRIDGE INSTITUTE OF

TECHNOLOGY-NORTH CAMPUS
Off International Airport Road, Kundana, Bengaluru -
562110

SUB : Object Oriented Programming With Java(BCS306A)


LAB MANUAL

PREPARED BY:
Prof. P Gopala Krishna
Department Of CSE CITNC
Object Oriented Programming with Java (BCS306A)

LabExp(1): (LEx1_MatrixAddCmdLine.java)
/* 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 LEx1_MatrixAddCmdLine


{
public static void main(String[] args)
{
int rowFirMat, colFirMat, rowSecMat, colSecMat //Declare matrix size

rowFirMat=Integer.parseInt(args[0]);
colFirMat=Integer.parseInt(args[1]);

rowSecMat=Integer.parseInt(args[2]);
colSecMat=Integer.parseInt(args[3]);
Scanner sc = new Scanner(System.in);

if (rowFirMat == rowSecMat && colFirMat == colSecMat)


{
int a[][] = new int[rowFirMat][colFirMat]; //Declare first matrix
int b[][] = new int[rowSecMat][colSecMat]; //Declare second matrix
int c[][] = new int[rowSecMat][colSecMat]; //Declare third matrix

//Initialize the first matrix


System.out.println("Enter all the elements of first matrix:");
for (int i = 0; i < rowFirMat; i++)
{
for (int j = 0; j < colFirMat; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.println("");

//Initialize the second matrix


System.out.println("Enter all the elements of second matrix:");
for (int i = 0; i < rowSecMat; i++)
{
for (int j = 0; j < colSecMat; j++)
{

Dept. Of CSE, CITNC Page|1


Object Oriented Programming with Java (BCS306A)

b[i][j] = sc.nextInt();
}
}
System.out.println("");

//Print the first matrix


System.out.println("First Matrix:");
for (int i = 0; i < rowFirMat; i++)
{
for (int j = 0; j < colFirMat; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println("");
}

//Print the second matrix


System.out.println("Second Matrix:");
for (int i = 0; i < rowSecMat; i++)
{
for (int j = 0; j < colSecMat; j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println("");
}

//Loop to add matrix elements


for (int i = 0; i < rowFirMat; i++)
{
for (int j = 0; j < colSecMat; j++)
{
for (int k = 0; k < colFirMat; k++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}

//Print the resultant matrix


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

Dept. Of CSE, CITNC Page|2


Object Oriented Programming with Java (BCS306A)

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


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

else
{
System.out.println("Addition not possible");
System.out.println("Try Again");
}
}
}

OUTPUT :
Enter all the elements of first matrix:
2
2
2
2

Enter all the elements of second matrix:


3
3
3
3

First Matrix:
22
22
Second Matrix:
33
33
Matrix after addition:
55
55

Dept. Of CSE, CITNC Page|3


Object Oriented Programming with Java (BCS306A)

LabExp(1): (LEx1_MatrixAdd.java)
/* Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from
Scanner) */
import java.util.Scanner;

public class LEx1_MatrixAdd


{
public static void main(String[] args)
{
int p, q, m, n; //Declare matrix size
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows in the first matrix:");
p = sc.nextInt(); //Initialize first matrix size
System.out.print("Enter the number of columns in the first matrix:");
q = sc.nextInt(); //Initialize first matrix size
System.out.print("Enter the number of rows in the second matrix:");
m = sc.nextInt(); //Initialize second matrix size
System.out.print("Enter the number of columns in the second matrix:");
n = sc.nextInt(); //Initialize second matrix size
if (p == m && q == n)
{
int a[][] = new int[p][q];
//Declare first matrix
int b[][] = new int[m][n];
//Declare second matrix
int c[][] = new int[m][n];
//Declare third matrix
//Initialize the first matrix
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] = sc.nextInt();
}
}
System.out.println("");

//Initialize the second matrix


System.out.println("Enter all the elements of second matrix:");
for (int i = 0; i < m; i++)
{

Dept. Of CSE, CITNC Page|4


Object Oriented Programming with Java (BCS306A)

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


{
b[i][j] = sc.nextInt();
}
}
System.out.println("");
//Print the first matrix
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("");
}

//Print the second matrix


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

//Loop to add matrix elements


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];
}
}
}
//Print the resultant matrix
System.out.println("Matrix after addition:");
for (int i = 0; i < p; i++)

Dept. Of CSE, CITNC Page|5


Object Oriented Programming with Java (BCS306A)

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

else
{
System.out.println("Addition not possible");
System.out.println("Try Again");
}
}
}

OUTPUT:

Enter the number of rows in the first matrix:2


Enter the number of columns in the first matrix:2
Enter the number of rows in the second matrix:2
Enter the number of columns in the second matrix:2
Enter all the elements of first matrix:
2
2
2
2

Enter all the elements of second matrix:


3
3
3
3

First Matrix:
22
22
Second Matrix:
33
33
Matrix after addition:

Dept. Of CSE, CITNC Page|6


Object Oriented Programming with Java (BCS306A)

55
55
LabExp(2): (LEx2_TestStack.java)
/* Develop a stack class to hold a maximum of 10 integers with suitable methods.
Develop a JAVA main method to illustrate Stack operations. */
class Stack {
private int stck[];
private int tos;
// allocate and initialize stack

Stack(int size) {
stck = new int[size];
tos = -1;
}

// Push an item onto the stack


void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

// Pop an item from the stack


int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class LEx2_TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack(5);
Stack mystack2 = new Stack(8);

// push some numbers onto the stack


for(int i=0; i<5; i++)
mystack1.push(i);
for(int i=0; i<8; i++)

Dept. Of CSE, CITNC Page|7


Object Oriented Programming with Java (BCS306A)

mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
OUTPUT :
Stack in mystack1:
4
3
2
1
0
Stack in mystack2:
7
6
5
4
3
2
1
0

Dept. Of CSE, CITNC Page|8


Object Oriented Programming with Java (BCS306A)

LabExp(3): (LEx3_TestEmployee.java)
/* 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. */

class Employee {
// private instance variable,not accessible from outside this class
private int id;
private String
name;
private double salary;

// Constructors (overloaded)
/** Constructs an Employee instance with default value for Id, name and Salary. */
public Employee() { // 1st (default) constructor
id = 5001;
name = "Rama";
salary = 80000.00;
}

/** Constructs a Circle instance with the given radius and default color */
public Employee(int id,String name,double salary) {
// 2nd (parameterised)constructor
this.id = id;
this.name = name;
this.salary = salary;
}
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setSalary(double salary){
this.salary=salary;
}

Dept. Of CSE, CITNC Page|9


Object Oriented Programming with Java (BCS306A)

public double getSalary(){


return salary;
}
/** returns the Annual salary of an Employee. */
public double getAnnualSalary(){
return (12*salary);
}
/** increases the salary by the given percentage. */
public double raiseSalary(int per) {
salary = salary + (salary*per)/100;
return salary;
}
public String toString(){
return id+" "+name+" "+salary;
}
}
public class LEx3_TestEmployee {
public static void main(String[] args) {
// Test constructor and toString()
Employee e1 = new Employee(5003, "Krishna", 250000.00);
System.out.println(e1); // toString();

//Test Setters and Getters


e1.setSalary(99999);
System.out.println(e1); // toString();
System.out.println("Id is: " + e1.getId());
System.out.println("Name is: " + e1.getName());
System.out.println("Salary is: " + e1.getSalary());

//Getting the anual salary of an employee...


System.out.println("Annual salary is: " + e1.getAnnualSalary()); // Test method

// Test raiseSalary() method


System.out.println(e1.raiseSalary(10));
System.out.println(e1);
}
}
OUTPUT:
5003 Gopal 250000.0
5003 Gopal 999.0
Id is: 5003
Name is: Gopal

Dept. Of CSE, CITNC P a g e | 10


Object Oriented Programming with Java (BCS306A)

Salary is: 999.0


Annual salary is: 11988.0
1098.9
5003 Gopal 1098.9
LabExp(4): (LEx4_TestMyPoint.java)
/* 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.*/
class MyPoint{
private int x;
private int y;

public MyPoint(){
x=4;
y=5;
}
public MyPoint(int x,int y){
this.x=x;
this.y=y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}

Dept. Of CSE, CITNC P a g e | 11


Object Oriented Programming with Java (BCS306A)

public int getX(){


return x;
}
public int getY(){
return y;
}
public void setXY(int x,int y){
this.x=x;
this.y=y;
}
public int[] getXY(){
int xy[]=new int[2];
xy[0]=this.x;
xy[1]=this.y;
return xy;
}

// Overloaded distance methods


public double distance(int x, int y) {
// Two int parameters
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}

public double distance(MyPoint another) {


// One MyPoint parameter
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}

public double distance() {


// No parameters
int xDiff = this.x - 0;
int yDiff = this.y - 0;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}
public String toString(){
//System.out.println("toString() called...");
return "("+this.x+","+this.y+")";
}

Dept. Of CSE, CITNC P a g e | 12


Object Oriented Programming with Java (BCS306A)

class LEx4_TestMyPoint
{
public static void main(String args[]){
System.out.println("Control in the main() programm ...");
MyPoint p1=new MyPoint();
System.out.println(p1);

p1.setX(8);
// Test setter for x
p1.setY(6);
// Test setter for y

System.out.println("x is: " + p1.getX());


// Test getter for x
System.out.println("y is: " + p1.getY());
// Test getter for y
System.out.println(p1);

System.out.println(" ");
MyPoint p2 = new MyPoint(0, 4);
// Test another constructor
System.out.println(p2);
// Test toString()
// Testing the overloaded methods distance()
System.out.println(p1.distance(p2));
// Overloaded distance() with MyPoint parameter
System.out.println(p2.distance(p1));
// Overloaded distance() with MyPoint parameter
System.out.println(p1.distance(5, 6));
// Overloaded distance() with x, y parameters
System.out.println(p1.distance());
// Overloaded distance() with no parameters
}
}
OUTPUT :
Control in the main() programm ...
(4,5)
x is: 8
y is: 6
(8,6)

Dept. Of CSE, CITNC P a g e | 13


Object Oriented Programming with Java (BCS306A)
LabExp(5): (LEx5_TestShape.java)
/*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.*/
class Shape{
void draw()
{
System.out.println("Drawing Shape");
}
void erase()
{
System.out.println("erasing Shape");
}
}
class Circle extends Shape{
void draw()
{
System.out.println("Drawing Circle");
}
void erase()
{
System.out.println("erasing Circle");
}
}
class Triangle extends Shape{
void draw()
{
System.out.println("Drawing Triangle");
}
void erase()
{
System.out.println("erasing Triangle");
}
}
class Square extends Shape{
void draw()
{
System.out.println("Drawing Square");
}
void erase()

Dept. Of CSE, CITNC P a g e | 14


Object Oriented Programming with Java (BCS306A)

{
System.out.println("erasing Square");
}
}
class LEx5_TestInheritance{
public static void main(String args[]){
Shape c=new Circle();
Shape t=new Triangle();
Shape s=new Square();
c.draw();
c.erase();
t.draw();
t.erase();
s.draw();
s.erase();
}
}
OUTPUT:
Drawing Circle
erasing Circle
Drawing Triangle
erasing Triangle
Drawing Square
erasing Square

Dept. Of CSE, CITNC P a g e | 15


Object Oriented Programming with Java (BCS306A)

LabExp(6): (LEx6_TestShape.java)
/*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. */

// Base class Shape


abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}

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

public Circle(double radius) {


this.radius = radius;
}

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

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

// Subclass Rectangle
class Rectangle extends Shape
{ private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override

Dept. Of CSE, CITNC P a g e | 16


Object Oriented Programming with Java (BCS306A)

public double getArea() {


return length * width;
}

@Override
public double getPerimeter() {
return 2 * (length + width);
}
}

// Subclass Triangle
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
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
}
public class LEx6_TestShape {
public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double rs1 = 4.0, rs2 = 6.0;
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Rectangle rectangle = new Rectangle(rs1, rs2);
Triangle triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);

Dept. Of CSE, CITNC P a g e | 17


Object Oriented Programming with Java (BCS306A)

System.out.println("Area of the Circle: " +circle.getArea());


System.out.println("Perimeter of the Circle:"+ circle.getPerimeter());
System.out.println("\nSides of the rectangle are:"+rs1+','+rs2);
System.out.println("Area of the Rectangle: " + rectangle.getArea());
System.out.println("Perimeter of the Rectangle: " + rectangle.getPerimeter());
System.out.println("\nSides of the Triangel are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.getArea());
System.out.println("Perimeter of the Triangle: " + triangle.getPerimeter());
}
}
OUTPUT :
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle:
25.132741228718345

Sides of the rectangle are: 4.0,6.0


Area of the Rectangle: 24.0
Perimeter of the Rectangle: 20.0

Sides of the Triangle are: 3.0,4.0,5.0


Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0

Dept. Of CSE, CITNC P a g e | 18


Object Oriented Programming with Java (BCS306A)

LabExp(7): (LEx7_TestResize.java)

/* 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 */

// 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("Width Resized to: " + width);
}

@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Height Resized to: " + height);
}

// Additional methods for Rectangle class


public int getWidth() {

Dept. Of CSE, CITNC P a g e | 19


Object Oriented Programming with Java (BCS306A)

return width;
}

public int getHeight() {


return height;
}

public void displayInfo() {


System.out.println("Rectangle: Width = " + width + ", Height = " + height);
}
}
// Testing the implementation
public class LEx7_TestResize {
public static void main(String[] args) {

// Creating a Rectangle object


Rectangle rectangle = new Rectangle(6, 9);

// Displaying the original information


System.out.println("Original Rectangle Info:");
rectangle.displayInfo();

// Resizing the rectangle


rectangle.resizeWidth(18);
rectangle.resizeHeight(3);

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}
OUTPUT :
Original Rectangle Info: Rectangle:
Width = 10, Height = 5 Resized
width to: 15
Resized height to: 8

Dept. Of CSE, CITNC P a g e | 20


Object Oriented Programming with Java (BCS306A)

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8
LabExp(8): (LEx8_TestOuterInner)
/* 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. */

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

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

public class LEx8_TestOuterInner {


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

Dept. Of CSE, CITNC P a g e | 21


Object Oriented Programming with Java (BCS306A)

Outer class display method


Inner class display method
LabExp(9): (LEx9_TestOuterInner)
/* Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally. */

// Custom exception class


class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}

public class LEx9_TestCustomException {


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

Dept. Of CSE, CITNC P a g e | 22


Object Oriented Programming with Java (BCS306A)

OUTPUT :1
Exception caught: Cannot divide by zero!
Finally block executed
OUTPUT :2
Result of division: 0.5
Finally block executed
LabExp(10): (LEx10_TestPackage)

/* Develop a JAVA program to create a package named mypack and import & implement

it in a suitable class. */

// Inside a folder named 'mypack'


package mypack;
public class MyPackageClass {
public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}
public static int addNumbers(int a, int b) {
return a + b;
}
}
// Main program outside the mypack folder
import mypack.MyPackageClass;
public class LEx10_TestPackage {
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);
}

Dept. Of CSE, CITNC P a g e | 23


Object Oriented Programming with Java (BCS306A)

}
To compile and run this program, you need to follow these steps:

i) Organize your directory structure as follows:

project-directory/

├── mypack/

│ └── MyPackageClass.java

└── PackageDemo.java
ii) Compile the files:

javac mypack/MyPackageClass.java

javac PackageDemo.java
OUTPUT :
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8

Dept. Of CSE, CITNC P a g e | 24


Object Oriented Programming with Java (BCS306A)

LabExp(11): (LEx11_TestRunnableThread.java)
/*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 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 TestRunnableThread{
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);

Dept. Of CSE, CITNC P a g e | 25


Object Oriented Programming with Java (BCS306A)

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();
}
}
OUTPUT :
Thread ID: 15 is running.
Thread ID: 18 is running.
Thread ID: 19 is running.
Thread ID: 17 is running.
Thread ID: 16 is running.

Dept. Of CSE, CITNC P a g e | 26


Object Oriented Programming with Java (BCS306A)

LabExp(12): (LEx12_ TestThreadConcurrent.java)


/* 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. */

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

public class TestThreadConcurrent {


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: " + i);
try {

Dept. Of CSE, CITNC P a g e | 27


Object Oriented Programming with Java (BCS306A)

Thread.sleep(500); // Sleep for 500 milliseconds


} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread
interrupted.");
}
}
}
}
OUTPUT :
Child
Thread
Count: 1
main
Thread
Count: 1
Child
Thread
Count: 2
main
Thread
Count: 2
Child
Thread
Count: 3
main
Thread
Count: 3
Child
Thread
Count: 4
main
Thread
Count: 4
Child
Thread
Count: 5
main
Thread
Dept. Of CSE, CITNC P a g e | 28
Object Oriented Programming with Java (BCS306A)
Count: 5
--- THE END ---

Dept. Of CSE, CITNC P a g e | 29

You might also like