VISVESVARAYA TECHNOLOGICAL UNIVERSITY
JNANASANGAMA BELGAVI-590018, KARNATAKA
Semester- IIIrd
OBJECT ORIENTED PROGRAMMING WITH JAVA
(BCS306A)
LAB MANUAL
Academic Year: 2025-2026
Prepared by
Annapurna Hudgi
[Link], Dept. of CSE(AIML)
BHEEMANNA KHANDRE INSTITUTE OF TECHNOLOGY BHALKI
Affiliated to Visvesvaraya Technological University- Belagavi
Department of Computer Science and Engineering
Academic Year: 2025-2026
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program01:MatrixAddition
DevelopaJAVAprogramtoaddTWOmatrices ofsuitableorderN(Thevalue of N
should be read from command line arguments).
JavaCode
import [Link];
publicclassMatrixAddition{
public static void main(String[] args) {
Scannerinput=newScanner([Link]);
[Link]("Enterthenumberofrowsforthematrices:"); int
rows = [Link]();
[Link]("Enterthenumberofcolumnsforthematrices:"); int
columns = [Link]();
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
int[][]resultMatrix=newint[rows][columns];
[Link]("Entertheelementsofthefirstmatrix:");
inputMatrixElements(matrix1, input);
[Link]("Entertheelementsofthesecondmatrix:");
inputMatrixElements(matrix2, input);
addMatrices(matrix1,matrix2,resultMatrix);
[Link]("Thesumofthematricesis:");
displayMatrix(resultMatrix);
[Link]();
}
publicstaticvoidinputMatrixElements(int[][]matrix,Scannerinput){ for
(int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[0].length; j++)
{[Link]("Enterelement ["+(i+1)+"]["+(j+1)+"]:");
matrix[i][j] = [Link]();
}
}
}
publicstaticvoidaddMatrices(int[][]matrix1,int[][]matrix2,int[][]resultMatrix){
Dept of CSE BKIT,Bhalki Page1
OOPS with Java (BCS306A)
Laboratory (BCS306A)
for (int i = 0; i < [Link]; i++) {
for(int j=0;j<matrix1[0].length;j++){
resultMatrix[i][j]=matrix1[i][j]+matrix2[i][j];
}
}
}
publicstaticvoiddisplayMatrix(int[][]matrix){
for (int i = 0; i < [Link]; i++) {
for(int j=0;j<matrix[0].length;j++){
[Link](matrix[i][j] + "");
}
[Link]();
}
}
}
Output
Enter the number of rows for the matrices: 2
Enterthenumberofcolumnsforthematrices:2 Enter
the elements of the first matrix:
Enterelement[1][1]:1
Enterelement[1][2]:2
Enterelement[2][1]:3
Enterelement[2][2]:4
Entertheelementsofthesecondmatrix: Enter
element [1][1]: 2
Enterelement[1][2]:4
Enterelement[2][1]:5
Enter element [2][2]:
6Thesumofthematricesis:
3 6
8 10
Dept of CSE BKIT,Bhalki Page2
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program02:Stack Operations
Developastackclasstoholdamaximumof10integerswithsuitablemethods.
Develop a JAVA main method to illustrate Stack operations.
JavaCode
[Link];
[Link];
public class Stack {
privatestaticfinalintMAX_SIZE=10;
private int[] stackArray;
private int top;
publicStack() {
stackArray=newint[MAX_SIZE];
top = -1;
}
publicvoidpush(intvalue){ if
(top <MAX_SIZE - 1) {
stackArray[++top] = value;
[Link]("Pushed:"+value);
}else{
[Link]("StackOverflow!Cannotpush"+value+".");
}
}
publicintpop(){ if
(top >= 0) {
int poppedValue = stackArray[top--];
[Link]("Popped:"+poppedValue);
return poppedValue;
}else{
[Link]("StackUnderflow!Cannotpopfromanemptystack."); return -
1; // Return a default value for simplicity
}
}
publicintpeek(){ if
(top >= 0) {
[Link]("Peeked:"+stackArray[top]);
return stackArray[top];
}else{
Dept of CSE BKIT,Bhalki Page3
OOPS with Java (BCS306A)
Laboratory (BCS306A)
[Link]("[Link]."); return
-1; // Return a default value for simplicity
}
}
publicvoiddisplay(){ if
(top >= 0) {
[Link]("StackContents:");
for (int i = 0; i <= top; i++) {
[Link](stackArray[i]+"");
}
[Link]();
}else{
[Link]("Stackisempty.");
}
}
publicbooleanisEmpty(){
return top == -1;
}
public boolean isFull() {
returntop==MAX_SIZE-1;
}
publicstaticvoidmain(String[]args){
Stack stack = new Stack();
Scannerscanner=newScanner([Link]); int
choice;
do{
[Link]("\nStack Menu:");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Peek");
[Link]("[Link]");
[Link]("[Link]");
[Link]("6. Check if the stack is full");
[Link]("0. Exit");
[Link]("Enter your choice: ");
choice=[Link]();
switch (choice) {
case1:
[Link]("Enterthevaluetopush:"); int
valueToPush = [Link]();
[Link](valueToPush);
break;
case2:
[Link]();
break;
case 3:
[Link]();
Dept of CSE BKIT,Bhalki Page4
OOPS with Java (BCS306A)
break;
Laboratory (BCS306A)
case4:
[Link]();
break;
case5:
[Link]("Isthestackempty?"+[Link]());
break;
case6:
[Link]("Isthestackfull?"+[Link]());
break;
case0:
[Link]("[Link]!");
break;
default:
[Link]("[Link].");
}
}while(choice!=0);
[Link]();
}
}
Dept of CSE BKIT,Bhalki Page5
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Output
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:4Stack
is empty.
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:5
Isthestackempty?true
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:6
Isthestackfull?false
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:1
Dept of CSE BKIT,Bhalki Page6
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Enterthevaluetopush:10
Pushed: 10
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:1
Enterthevaluetopush:20
Pushed: 20
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:4
StackContents:1020
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:3
Peeked: 20
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:1
Dept of CSE BKIT,Bhalki Page7
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Enterthevaluetopush:30
Pushed: 30
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enter your choice: 4
StackContents:102030
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:2
Popped: 30
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:3
Peeked: 20
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
0. Exit
Enteryourchoice:4
StackContents:1020
Dept of CSE BKIT,Bhalki Page8
OOPS with Java (BCS306A)
Laboratory (BCS306A)
StackMenu:
1. Push
2. Pop
3. Peek
4. DisplayStackContents
5. Checkifthestackisempty
6. Checkifthestackisfull
[Link]
Enteryourchoice:0
[Link]!
Dept of CSE BKIT,Bhalki Page9
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program03:EmployeeClass
AclasscalledEmployee,which modelsanemployee withanID,nameand salary, is
designed as shown in the following class diagram. The method
raiseSalary(percent)[Link]
Employee class and suitable main method for demonstration.
JavaCode
[Link];
publicclassEmployee{ private
int id;
private String name;
privatedoublesalary;
// Constructor
publicEmployee(intid,Stringname,doublesalary){ [Link] =
id;
[Link] = name;
[Link]=salary;
}
// Getter methods
publicintgetId(){
returnid;
}
publicStringgetName(){
return name;
}
publicdoublegetSalary(){
return salary;
}
//Methodtoraisesalarybyagivenpercentage
public void raiseSalary(double percent) {
if(percent>0){
salary+=salary* (percent/ 100);
[Link](name+"'ssalaryhas beenincreasedby"+percent+"%.");
}else{
[Link]("[Link].");
}
}
Dept of CSE BKIT,Bhalki Page10
OOPS with Java (BCS306A)
Laboratory (BCS306A)
// Main method for demonstration
publicstaticvoidmain(String[]args){
//CreateanEmployee object
// Employee employee = new Employee(101, "John Doe", 50000.0);
Employeeemployee=newEmployee(101,"JohnDoe",50000.0);
// Display initial details
[Link]("InitialDetails:");
displayEmployeeDetails(employee);
//Raisethesalaryby10%
[Link](10);
// Display details after the salary raise
[Link]("\nDetailsAfterSalaryRaise:");
displayEmployeeDetails(employee);
}
//Helpermethodtodisplayemployeedetails
privatestaticvoiddisplayEmployeeDetails(Employeeemployee){
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Salary: $" + [Link]());
}
}
Output
InitialDetails:
ID:101
Name:JohnDoe
Salary:$50000.0
JohnDoe'ssalaryhasbeen increasedby10.0%.
DetailsAfterSalaryRaise:
ID: 101
Name:JohnDoe
Salary:$55000.0
Dept of CSE BKIT,Bhalki Page11
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program04:2DPointClass
AclasscalledMyPoint,whichmodelsa2Dpointwithxandycoordinates,is designed
as follows:
Twoinstancevariablesx(int)andy(int).
Adefault(or“no-arg”)constructorthatconstructapointatthedefault
location of (0, 0).
Aoverloadedconstructorthatconstructsapointwiththegivenxandy
coordinates.
AmethodsetXY()tosetbothxandy.
AmethodgetXY()whichreturnsthexandyina2-elementintarray.
AtoString()methodthatreturnsastring descriptionoftheinstanceinthe
format “(x, y)”.
Amethodcalleddistance(intx,inty)thatreturnsthedistancefromthispointto
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
pointtotheorigin(0,0)[Link]
program (called TestMyPoint) to test all the methods defined in the class.
JavaCode
package [Link];
publicclassMyPoint{
privateintx;
privateinty;
//Defaultconstructor
public MyPoint() {
this.x=0;
this.y=0;
}
// Overloaded constructor
publicMyPoint(intx,inty){
this.x=x;
this.y=y;
}
//Methodtosetbothxandy
Dept of CSE BKIT,Bhalki Page12
OOPS with Java (BCS306A)
Laboratory (BCS306A)
publicvoidsetXY(intx,inty){ this.x
= x;
this.y=y;
}
//Methodtoreturnthexand yina2-element intarray public
int[] getXY() {
returnnew int[]{x,y};
}
//toStringmethod
@Override
publicStringtoString(){
return"("+x+","+y+")";
}
//Methodto calculatedistancefromthispoint toanotherpoint (x,y)
public double distance(int x, int y) {
intdx=this.x-x;
intdy= this.y-y;
[Link](dx* dx+dy*dy);
}
//OverloadedmethodtocalculatedistancefromthispointtoanotherMyPoint instance public
double distance(MyPoint another) {
returndistance(another.x,another.y);
}
//Anotheroverloaded methodtocalculatedistance fromthispointtotheorigin(0,0) public
double distance() {
returndistance(0,0);
}
//Mainmethodfortesting
publicstaticvoid main(String[]args){
// Create instances of MyPoint
MyPoint point1 = new MyPoint();
MyPointpoint2=newMyPoint(3,4);
//Displayinitialpoints
[Link]("Point1:"+[Link]());
[Link]("Point2:"+[Link]());
//Setnewcoordinatesforpoint1
[Link](1, 2);
[Link]("Newcoordinates forPoint1:"+[Link]());
Dept of CSE BKIT,Bhalki Page13
OOPS with Java (BCS306A)
Laboratory (BCS306A)
// Display coordinates as an array
int[]coordinates=[Link]();
[Link]("CoordinatesofPoint 2asarray:["+coordinates[0]+","+
coordinates[1] + "]");
//Calculateanddisplaydistances
[Link]("Distance from Point 1 to (0, 0): " + [Link]());
[Link]("DistancefromPoint 2toPoint 1:"+[Link](point1));
[Link]("Distance from Point 1 to (3, 4): " + [Link](3, 4));
}
Output
Point1:(0,0)
Point2:(3,4)
NewcoordinatesforPoint1:(1,2)
CoordinatesofPoint2 asarray:[3,4]
DistancefromPoint1to(0,0): 2.23606797749979
Distance fromPoint2toPoint1:2.8284271247461903
DistancefromPoint1to(3,4): 2.8284271247461903
Dept of CSE BKIT,Bhalki Page14
OOPS with Java (BCS306A)
Laboratory (BCS306A)
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 nameddraw()anderase().Demonstrate polymorphismconceptsby
developing suitable methods, defining member data and main program
Java Code
[Link];
class Shape {
//Memberfunctions
publicvoiddraw(){
[Link]("Drawingashape");
}
public void erase() {
[Link]("Erasingashape");
}
}
classCircleextendsShape{
//OverridedrawmethodforCircle @Override
public void draw() {
[Link]("Drawingacircle");
}
//OverrideerasemethodforCircle @Override
public void erase() {
[Link]("Erasingacircle");
}
}
classTriangleextendsShape{
//OverridedrawmethodforTriangle
@Override
public void draw() {
[Link]("Drawingatriangle");
}
//OverrideerasemethodforTriangle
@Override
publicvoiderase(){
Dept of CSE BKIT,Bhalki Page15
OOPS with Java (BCS306A)
Laboratory (BCS306A)
[Link]("Erasingatriangle");
}
}
classSquareextendsShape{
//OverridedrawmethodforSquare @Override
public void draw() {
[Link]("Drawingasquare");
}
//OverrideerasemethodforSquare @Override
public void erase() {
[Link]("Erasingasquare");
}
}
publicclassShapeDemo{
publicstaticvoid main(String[]args){
//CreateanarrayofShapeobjects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
//Demonstratepolymorphismbycallingdrawanderase methodsoneachshape for
(Shape shape : shapes) {
[Link]();
[Link]();
[Link]();//Addanewlineforbetterreadability
}
}
}
Dept of CSE BKIT,Bhalki Page16
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Output
Drawingacircle
Erasingacircle
Drawingatriangle
Erasingatriangle
Drawingasquare
Erasingasquare
Dept of CSE BKIT,Bhalki Page17
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program05:AbstractClass
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 [Link];
abstractclassShape{
//Abstractmethods
public abstract double calculateArea();
publicabstractdoublecalculatePerimeter();
}
//SubclassCircle
classCircleextendsShape{
private double radius;
//Constructor
publicCircle(doubleradius){
[Link] = radius;
}
//Implementationofabstractmethods @Override
public double calculateArea() {
[Link]*radius*radius;
}
@Override
publicdoublecalculatePerimeter(){
return 2 * [Link] * radius;
}
}
//SubclassTriangle
class Triangle extends Shape {
privatedoubleside1,side2,side3;
//Constructor
publicTriangle(doubleside1,doubleside2,doubleside3){ this.side1
= side1;
this.side2=side2;
this.side3= side3;
Dept of CSE BKIT,Bhalki Page18
OOPS with Java (BCS306A)
}
Laboratory (BCS306A)
//Implementationofabstractmethods
@Override
publicdoublecalculateArea(){
//Heron'sformulaforareaofatriangle double s
= (side1 + side2 + side3) / 2;
[Link](s*(s-side1)* (s-side2)* (s-side3));
}
@Override
publicdoublecalculatePerimeter(){
return side1 + side2 + side3;
}
}
//Mainclassfordemonstration
public class ShapeDemo {
publicstaticvoidmain(String[]args){
//CreateinstancesofCircleandTriangle Circle
circle = new Circle(5.0);
Triangletriangle= newTriangle(3.0,4.0,5.0);
// Display information about Circle
[Link]("Circle:");
[Link]("Area:"+[Link]());
[Link]("Perimeter:"+[Link]());
// Display information about Triangle
[Link]("\nTriangle:");
[Link]("Area:"+[Link]());
[Link]("Perimeter:"+[Link]());
}
}
Output
Circle:
Area:78.53981633974483
Perimeter:31.41592653589793
Triangle:
Area:6.0
Perimeter:12.0
Dept of CSE BKIT,Bhalki Page19
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program07:Resizableinterface
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
packagecom.prcts1;
interfaceResizable{
void resizeWidth(int width);
voidresizeHeight(intheight);
}
//ClassRectangleimplementingResizableinterface
class Rectangle implements Resizable {
private int width;
privateint height;
//Constructor
publicRectangle(intwidth,intheight){
[Link] = width;
[Link]= height;
}
// Getter methods
publicintgetWidth(){
returnwidth;
}
publicintgetHeight(){
return height;
}
//ImplementationofResizableinterfacemethods @Override
publicvoidresizeWidth(intwidth){ if
(width > 0) {
[Link]=width;
[Link]("Widthresizedto: "+width);
}else{
[Link]("[Link].");
}
Dept of CSE BKIT,Bhalki Page20
OOPS with Java (BCS306A)
}
Laboratory (BCS306A)
@Override
publicvoidresizeHeight(intheight){ if
(height > 0) {
[Link]= height;
[Link]("Heightresizedto:"+height);
}else{
[Link]("[Link].");
}
}
}
//Mainclassfordemonstration public
class ResizableDemo {
publicstaticvoidmain(String[]args){
//CreateaninstanceofRectangle
Rectanglerectangle=newRectangle(10, 5);
// Display initial dimensions
[Link]("InitialDimensions:");
displayRectangleDimensions(rectangle);
// Resize widthand height
[Link](15);
[Link](8);
// Display dimensions after resizing
[Link]("\nDimensionsAfterResizing:");
displayRectangleDimensions(rectangle);
}
//Helpermethodtodisplayrectangledimensions
privatestaticvoiddisplayRectangleDimensions(Rectanglerectangle){
[Link]("Width: " + [Link]());
[Link]("Height: " + [Link]());
}
Dept of CSE BKIT,Bhalki Page21
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Output
InitialDimensions:
Width: 10
Height:5
Widthresizedto:15
Height resized to: 8
DimensionsAfterResizing:
Width: 15
Height:8
Dept of CSE BKIT,Bhalki Page22
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program08:Outerclass
Develop a JAVA program to create an outer class with a function display.
Createanotherclassinsidethe outerclassnamedinner withafunctioncalled
display and call the two functions in the main class.
JavaCode
packagecom.prcts1;
class Outer {
//Outerclassdisplayfunction
void display() {
[Link]("Outerclassdisplay");
}
//Innerclass
classInner{
//Innerclassdisplayfunction void
display() {
[Link]("Innerclassdisplay");
}
}
}
//Mainclass
publicclassOuterInnerDemo{
publicstaticvoidmain(String[]args){
//Createaninstanceoftheouterclass Outer
outerObj = new Outer();
//Callthedisplayfunctionoftheouterclass
[Link]();
//Createaninstanceofthe innerclassusingtheouterclassinstance
[Link] innerObj = [Link] Inner();
//Callthedisplayfunctionoftheinnerclass
[Link]();
}
Dept of CSE BKIT,Bhalki Page23
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Output
Outerclassdisplay
Inner class display
Dept of CSE BKIT,Bhalki Page24
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program09:CustomException
DevelopaJAVAprogramtoraiseacustomexception(userdefinedexception) for
DivisionByZero using try, catch, throw and finally.
JavaCode
packagecom.prcts1;
classDivisionByZeroExceptionextendsException{
publicDivisionByZeroException(Stringmessage){
super(message);
}
}
//Mainclass
publicclassCustomExceptionExample{
//Methodthatperformsdivisionandraisesthecustomexception
publicstaticdoubleperformDivision(intnumerator,intdenominator)throws DivisionByZeroException
{
if(denominator== 0){
thrownewDivisionByZeroException("Divisionbyzeroisnotallowed.");
}
return(double)numerator/ denominator;
}
publicstaticvoidmain(String[]args){ try
{
//Attemptingtoperformdivision int
numerator = 10;
intdenominator=0;
doubleresult=performDivision(numerator,denominator);
[Link]("Result of division: " + result);
}catch(DivisionByZeroExceptione){
// Catching the custom exception
[Link]("Exceptioncaught:"+[Link]());
}finally{
//Codeinthefinallyblockwillexecutewhetheranexceptionoccursornot
[Link]("Finally block executed.");
}
}
}
Dept of CSE BKIT,Bhalki Page25
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Output
Exceptioncaught:Divisionbyzeroisnotallowed. Finally
block executed.
Dept of CSE BKIT,Bhalki Page26
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program10:Packages
DevelopaJAVAprogramtocreateapackage namedmypackandimport&
implement it in a suitable class.
Java Code
package mypack;
publicclassMyClass{
public void displayMessage() {
[Link]("[Link]!");
}
}
//CREATE NEWPACKAGE
package pack;
[Link];
public class MainClass {
publicstatic voidmain(String[]args){
//Creatinganobject ofMyClassfromthe mypackpackage
MyClass myObject = new MyClass();
//CallingthedisplayMessagemethodfromMyClass
[Link]();
}
}
OUTPUT
[Link]!
Dept of CSE BKIT,Bhalki Page27
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program11:RunnableInterface
Write a program to illustrate creation of threads using runnable class. (start
methodstarteachofthe [Link] sleep()
for suspend the thread for 500 milliseconds).
Java Code
packagepack;
classMyRunnableimplementsRunnable{
private String threadName;
//Constructortosetthethreadname
public MyRunnable(String name) {
[Link]=name;
}
//Therunmethodcontainsthecodethatwillbeexecutedinthenewthread @Override
publicvoidrun(){
try {
for (int i = 1; i <= 5; i++) {
[Link](threadName+":Count"+i);
[Link](500);//Suspend thethread for 500 milliseconds
}
} catch (InterruptedException e) {
[Link](threadName+"interrupted.");
}
}
}
public class RunnableThreadExample {
publicstaticvoidmain(String[]args){
//CreatinginstancesofMyRunnableandpassingthreadnames
MyRunnable myRunnable1 = new MyRunnable("Thread 1");
MyRunnable myRunnable2 = new MyRunnable("Thread 2");
//Creatingthreadsandassigningrunnableobjects
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
//Startingthethreads
[Link]();
Dept of CSE BKIT,Bhalki Page28
OOPS with Java (BCS306A)
[Link]();
Laboratory (BCS306A)
}}
Output
Thread2:Count1
Thread1:Count1
Thread2:Count2
Thread1:Count2
Thread2:Count3
Thread1:Count3
Thread2:Count4
Thread1:Count4
Thread1:Count5
Thread2:Count5
Dept of CSE BKIT,Bhalki Page29
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Program12:ThreadClass
DevelopaprogramtocreateaclassMyThreadinthisclassaconstructor, 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
packagepack;
classMyThreadextendsThread{
//ConstructorofMyThreadclass
publicMyThread(Stringname){
super(name);//Callingthebaseclassconstructorusingsuper start();
// Start the thread
}
//Therunmethodcontainsthecodethatwillbeexecutedinthenewthread @Override
publicvoidrun(){
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName()+":Count"+i); try {
[Link](500);//Suspend thethreadfor 500 milliseconds
} catch (InterruptedException e) {
[Link]([Link]().getName()+"interrupted.");
}
}
}
}
publicclassThreadExample{
publicstaticvoid main(String[]args){
//Creating an instanceofMyThread
MyThread myThread=newMyThread("ChildThread");
// Code in the main thread
for(inti=1; i<=5; i++){
[Link]([Link]().getName()+":Count"+i); try {
[Link](500);//Suspendthemainthreadfor500milliseconds
}
Dept of CSE BKIT,Bhalki Page30
OOPS with Java (BCS306A)
Laboratory (BCS306A)
catch (InterruptedException e) {
[Link]([Link]().getName()+"interrupted.");
}
}
}
}
OUTPUT
main:Count1
ChildThread:Count1
ChildThread:Count2
main: Count 2
ChildThread:Count3
main: Count 3
main:Count4
ChildThread:Count4
main: Count 5
ChildThread:Count
Dept of CSE BKIT,Bhalki Page31
OOPS with Java (BCS306A)
Laboratory (BCS306A)
Dept of CSE BKIT,Bhalki Page32