0% found this document useful (0 votes)
27 views15 pages

Java Lab Manual for 3rd Sem ISE

Uploaded by

moh24amme
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views15 pages

Java Lab Manual for 3rd Sem ISE

Uploaded by

moh24amme
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

--------------

BMS Institute of Technology


Yelahanka, Bangalore-560 064

Object Oriented Programming with JAVA


BCS306A
Laboratory Manual
For
3th Semester B.E
Information Science & Engineering

Department of Information Science & Engineering


BMS Institute of Technology
Yelahanka, Bangalore-560 064

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

CONTENTS

[Link] Particulars [Link]


1 Lab Instructions 1
2 Introduction
3 Develop a JAVA program to add TWO matrices of suitable order N (The value of
N should be read from command line arguments).

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


Develop a JAVA main method to illustrate Stack operations.

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

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

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


for DivisionByZero using try, catch, throw and finally.

9 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).
10 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
11 Viva questions

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from command
line arguments).

Program1 :

import [Link];
class AddMatrix
{
public static void main(String args[])
{
int i,j;
Scanner in = new Scanner([Link]);

int row = [Link](args[0]);


int col = [Link](args[1]);

int mat1[][] = new int[row][col];


int mat2[][] = new int[row][col];
int res[][] = new int[row][col];
[Link]("Enter the elements of matrix1");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
mat1[i][j] = [Link]();
[Link]();
}
[Link]("Enter the elements of matrix2");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
mat2[i][j] = [Link]();
[Link]();
}
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
res[i][j] = mat1[i][j] + mat2[i][j] ;
[Link]("Sum of matrices:-");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
[Link](res[i][j]+"\t");
[Link]();
}
}
}

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

Result:

java AddMatrix 2 2
Enter the elements of matrix1
1
1

1
1

Enter the elements of matrix2


2
2

2
2

Sum of matrices:-
3 3
3 3

2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main method to
illustrate Stack operations.

Program2:
import [Link].*;
public class Stack {
int arr[];
int top;
int size = 10;
Stack()
{
arr = new int[size];
top = -1;
}
void push(int num)
{
if(top == size - 1)
[Link]("Stack OVERFLOW");
else
arr[++top] = num;
}
int pop()
{
if(top == -1)
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

{
[Link]("Stack UNDERFLOW");
return 0;
}
else
{
int n = arr[top];
top--;
return n;
}
}
void display()
{
for(int i=0; i<=top; i++)
[Link](arr[i]);
}
public static void main(String args[])
{
Stack s = new Stack();
Scanner sc= new Scanner([Link]);
int item, ch;
String yn;
do
{
[Link]("Enter your choice");
[Link]("[Link] \n [Link] \n [Link] \n
[Link]");
ch = [Link]();
switch(ch)
{
case 1: [Link]("Enter element to be
pushed");
item = [Link]();
[Link](item);
break;
case 2: item = [Link]();
[Link]("Item popped = " + item);
break;
case 3: [Link]("Contents of Stack");
[Link]();
break;
case 4: [Link]("Thank you");
[Link](0);
break;
default: [Link]("Invalid choice");
break;
}
[Link]("Would you like to continue?

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

(y/Y)");
yn = [Link]();
}while([Link]("y") || [Link]("Y"));
[Link]("Thank you");
}
}

Result:

Enter your choice


1
Enter element to be pushed
2
Would you like to continue? (y/Y)
y
Enter your choice
[Link]
[Link]
[Link]
[Link]
1
Enter element to be pushed
4
Would you like to continue? (y/Y)
y
Enter your choice
[Link]
[Link]
[Link]
[Link]
1
Enter element to be pushed
6
Would you like to continue? (y/Y)
y
[Link]
[Link]
[Link]
[Link]
3
Contents of Stack
2
4
6
Would you like to continue? (y/Y)
y
Enter your choice
[Link]
[Link]
[Link]
[Link]
2
Item popped = 6
Would you like to continue? (y/Y)

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

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

Program3:

class Shape {
protected String name;

public Shape(String name) {


[Link] = name;
}

public void draw() {


[Link]("Drawing a " + name);
}

public void erase() {


[Link]("Erasing a " + name);
}
}

class Circle extends Shape {


private double radius;

public Circle(String name, double radius) {


super(name);
[Link] = radius;
}

@Override
public void draw() {
[Link]("Drawing a circle with radius " + radius);
}

@Override
public void erase() {
[Link]("Erasing a circle with radius " + radius);
}
}

class Triangle extends Shape {


private double base;
private double height;

public Triangle(String name, double base, double height) {


super(name);
[Link] = base;
[Link] = height;
}

@Override
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

public void draw() {


[Link]("Drawing a triangle with base " + base + " and height " + height);
}

@Override
public void erase() {
[Link]("Erasing a triangle with base " + base + " and height " + height);
}
}

class Square extends Shape {


private double side;

public Square(String name, double side) {


super(name);
[Link] = side;
}

@Override
public void draw() {
[Link]("Drawing a square with side length " + side);
}

@Override
public void erase() {
[Link]("Erasing a square with side length " + side);
}
}

public class ShapeDemo {


public static void main(String[] args) {
Shape[] shapes = new Shape[3];

shapes[0] = new Circle("Circle", 5.0);


shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);

for (Shape shape : shapes) {


[Link]();
[Link]();
[Link]();
}
}
}

Result:

Drawing a circle with radius 5.0


Erasing a circle with radius 5.0

Drawing a triangle with base 4.0 and height 6.0


Erasing a triangle with base 4.0 and height 6.0

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

Drawing a square with side length 3.0


Erasing a square with side length 3.0

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

Program 4:

// [Link]
// Abstract class Shape
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}

// [Link]
// Subclass Circle
class Circle extends Shape {
private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
double calculateArea() {
return [Link] * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * [Link] * radius;
}
}
// [Link]
// 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
double calculateArea() {
double s = (side1 + side2 + side3) / 2; // Semi-perimeter
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

return [Link](s * (s - side1) * (s - side2) * (s - side3));


}

@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
// [Link]
// Subclass Main

public class Main {


public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Triangle triangle = new Triangle(ts1, ts2, ts3);
[Link]("Radius of the Circle"+r);
[Link]("Area of the Circle: " + [Link]());
[Link]("Perimeter of the Circle: " + [Link]());
[Link]("\nSides of the Traiangel are: "+ts1+','+ts2+','+ts3);
[Link]("Area of the Triangle: " + [Link]());
[Link]("Perimeter of the Triangle: " + [Link]());
}
}

Result:
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345

Sides of the Traiangel are: 3.0,4.0,5.0


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

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

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

// [Link]
// Interface Resizable

// Declare the Resizable interface


interface Resizable {
// Declare the abstract method "resizeWidth" to resize the width
void resizeWidth(int width);

// Declare the abstract method "resizeHeight" to resize the height


void resizeHeight(int height);
}
// [Link]

// Declare the Rectangle class, which implements the Resizable interface


class Rectangle implements Resizable {
// Declare private instance variables to store width and height
private int width;
private int height;

// Constructor for initializing the width and height


public Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}

// Implement the "resizeWidth" method to resize the width


public void resizeWidth(int width) {
[Link] = width;
}

// Implement the "resizeHeight" method to resize the height


public void resizeHeight(int height) {
[Link] = height;
}

// Method to print the current width and height of the rectangle


public void printSize() {
[Link]("Width: " + width + ", Height: " + height);
}
}
// [Link]

// Declare the Main class


public class Main {
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

public static void main(String[] args) {


// Create an instance of the Rectangle class with an initial size
Rectangle rectangle = new Rectangle(100, 150);

// Print the initial size of the rectangle


[Link]();

// Resize the rectangle by changing its width and height


[Link](150);
[Link](200);

// Print the updated size of the rectangle


[Link]();
}
}

Result:

Width: 100, Height: 150


Width: 150, Height: 200

6. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero using try, catch,
throw and finally.

class MyException extends Exception


{
private int ex;
MyException(int b)
{
ex=b;
}
public String toString()
{
return "My Exception : Number is not divided by "+ex;
}
}
class DivideByZeroException
{
static void divide(int a,int b) throws MyException
{
if(b<=0)
{
throw new MyException(b);
}
else
{
[Link]("Division : "+a/b);
}
}
public static void main(String arg[])
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

{
try
{
divide(10,0);
}
catch(MyException me)
{
[Link](me);
}
}
}

Result:

My Exception : Number is not divided by 0

7. 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 [Link]()
[Link](500);
[Link]("Thread ID: " + [Link]().getId() + " is running.");
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
public void stopThread() {
running = false;
}
}
public class p7 {
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


[Link]();
[Link]();
[Link]();
[Link]();
[Link]();

// Sleep for a while to allow the threads to run

Result:

Thread ID: 10 is running.


Thread ID: 12 is running.
Thread ID: 11 is running.
Thread ID: 13 is running.
Thread ID: 14 is running.
Thread ID: 10 is running.
Thread ID: 12 is running.
Thread ID: 11 is running.
Thread ID: 13 is running.

8. 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++) {
[Link]([Link]().getName() + " Count: " + i);
try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link]([Link]().getName() + " Thread interrupted.");
}
>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------
--------------

}
}
}

public class p8 {
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++) {
[Link]([Link]().getName() + " Thread Count: " + i);
try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link]([Link]().getName() + " Thread interrupted.");
}
}
}

Result:

main Thread Count: 1


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

>>>>>>>>>>>>>>>>>>>>>-------
___--------------------------------------------------------------------------------------------___________________------------

Common questions

Powered by AI

The MyThread class extends the Thread class and overrides its run() method to define the task performed by the thread. The constructor calls start(), which invokes the run() method asynchronously. In the main method, after creating a MyThread instance, the main thread continues execution separately. With both threads calling Thread.sleep(500) to pause for 500 milliseconds within loops, this setup allows child and main threads to execute concurrently. The output reflects interleaved execution of both threads, illustrating parallel processing .

Polymorphism is applied through method overriding in subclasses Circle and Triangle that extend the abstract class Shape. The abstract class Shape defines the calculateArea() and calculatePerimeter() methods without providing implementations. Each subclass provides its specific implementation: Circle calculates area and perimeter using properties of a circle, while Triangle uses Heron's formula to calculate area and sums all sides for the perimeter. Thus, call to calculateArea() or calculatePerimeter() on a Shape reference at runtime will invoke the appropriate subclass's method, demonstrating polymorphism .

Implementing the Resizable interface in the Rectangle class allows it to change its dimensions independently of its core structure. The interface mandates implementation of resizeWidth(int width) and resizeHeight(int height) methods, which Rectangle then uses to adjust its dimensions. This demonstrates Java interface usage by defining contract methods that classes implement. Interfaces provide a way to achieve abstraction and multiple inheritance, enabling flexibility in system design where different classes can implement the interface methods according to their needs .

The matrix addition program accepts command line arguments to define matrix dimensions dynamically. It uses Integer.parseInt(args[0]) and Integer.parseInt(args[1]) to parse the first two command-line inputs as the number of rows and columns for both matrices. This design lets the user specify matrix size upon execution, making the code flexible to handle matrices of various dimensions, rather than hardcoding specific sizes. Hence, it enhances usability and reusability by adapting to input variations from the command line .

The interface Resizable and its implementation by the Rectangle class illustrate the principle of Interface Segregation in object-oriented design. This principle suggests creating specific interfaces for different functionalities, enabling classes like Rectangle to implement only the interfaces they need. Resizable thus defines capabilities related solely to resizing, separating these functionalities and ensuring modularity. Rectangle implements this interface, segregating resizing concerns from other potential functionalities. This setup promotes a clear contract of capabilities, organizing code in a maintainable and structured manner .

The Java stack class designed in the program handles overflow and underflow through simple control flow checks. For overflow, when the push method is called, it checks if the stack's top index has reached the size-1 (indicating the stack is full), and if so, it prints 'Stack OVERFLOW'. For underflow, within the pop method, it checks if the top equals -1, meaning the stack is empty, and prints 'Stack UNDERFLOW' instead of proceeding to pop an element .

The program demonstrates polymorphism by allowing objects of different classes (Circle, Triangle, Square) to be treated as objects of the superclass (Shape). The Shape class defines methods draw() and erase(), which are overridden in each subclass to provide specific behavior according to the shape's properties. In the main program, an array of Shape is created that holds different subclasses. When iterating over this array, each subclass’s overridden methods are called, showing polymorphism as each subclass behaves differently when draw() or erase() is executed .

Custom exceptions in Java allow programs to signal specific error conditions and thus handle domain-specific errors more precisely. The DivisionByZeroException program enhances robustness by defining a MyException class for cases where a divisor is zero. Instead of allowing a division by zero runtime exception, the program throws MyException with a meaningful message, catching it to avoid termination. This approach enables developers to provide context-specific messages and handle errors gracefully, improving code reliability and maintainability .

The sleep method in Java temporarily suspends a thread for a specified duration without releasing its locks, allowing other threads to execute. It helps manage CPU time by pausing threads during non-critical operations. However, potential pitfalls include inaccurate timekeeping due to thread scheduling variability and the InterruptedException, which can indicate thread interruption. Correct management of sleep through try-catch ensures robust thread control, but developers must carefully synchronize and manage shared resources to avoid concurrency issues .

Overriding draw and erase methods in Shape subclasses (Circle, Triangle, Square) allows them to exhibit unique behaviors while using a common interface defined by the parent class. This approach leverages polymorphism, enabling dynamic method dispatch. A critical advantage is code maintainability—method logic specific to each shape is centralized in its respective class, enhancing readability and reducing the need for conditional logic elsewhere. Changes and enhancements to specific shapes can be confined to their class definitions without affecting other parts of the program .

You might also like