0% found this document useful (0 votes)
11 views21 pages

Java Lab Manual: Matrix & Stack Operations

The document discusses four Java programs: 1) Adding two matrices of a given order N, 2) Developing a stack class to hold integers with methods like push, pop, peek etc, 3) Developing an Employee class with methods to set and get employee details and raise salary by a percentage, 4) Developing a Point class with methods to set and get coordinates and calculate distance between points.

Uploaded by

Vivek S
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)
11 views21 pages

Java Lab Manual: Matrix & Stack Operations

The document discusses four Java programs: 1) Adding two matrices of a given order N, 2) Developing a stack class to hold integers with methods like push, pop, peek etc, 3) Developing an Employee class with methods to set and get employee details and raise salary by a percentage, 4) Developing a Point class with methods to set and get coordinates and calculate distance between points.

Uploaded by

Vivek S
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

OOP WITH JAVA LABOTRATORY(BCS306A)

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

Aim: Demonstrating creation of java classes, objects, declaration and initialization of


variables.

import [Link];

public class Matrix {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter the value of N: ");
int N = [Link]();

int[][] firstMatrix = new int[N][N];


int[][] secondMatrix = new int[N][N];
int[][] resultMatrix = new int[N][N];

[Link]("Enter the elements of first matrix: ");


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
firstMatrix[i][j] = [Link]();
}
}

[Link]("Enter the elements of second matrix: ");


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
secondMatrix[i][j] = [Link]();
}
}

for (int i = 0; i < N; i++) {


for (int j = 0; j < N; j++) {
resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}

[Link]("The resultant matrix is: ");


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
[Link](resultMatrix[i][j] + " ");
}
[Link]();

Dept. of ISE, JSSATEB Page:5


OOP WITH JAVA LABOTRATORY(BCS306A)
}
}
}

OUTPUT
1. Enter the value of N:
2
Enter the elements of first matrix:
34
45
Enter the elements of second matrix:
56
78
The resultant matrix is:
11 10
11 13
2. Enter the value of N:
3
Enter the elements of first matrix:
345
567
10 22 45
Enter the elements of second matrix:
67 8 9
346
3 67 8
The resultant matrix is:
70 12 14
8 10 13
12 89 53

Dept. of ISE, JSSATEB Page:5


OOP WITH JAVA LABOTRATORY(BCS306A)
Program:2.
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.

Aim: Demonstrating creation of java classes, objects, constructors, declaration and


initialization of variables.
public class Stack_Operations {
private int[] stack;
private int top;
private int maxSize;
public Stack_Operations(int maxSize) {
[Link] = maxSize;
stack = new int[maxSize];
top = -1;
}

public void push(int item) {


if (!isFull()) {
stack[++top] = item;
} else {
[Link]("Stack is full");
}
}

public int pop(int i) {


if (!isEmpty()) {
return stack[top--];
} else {
[Link]("Stack is empty");
return -1;
}
}

public int peek() {


if (!isEmpty()) {
return stack[top];
} else {
[Link]("Stack is empty");
return -1;
}

[Link] ISE, JSSATEB Page:9


OOP WITH JAVA LABOTRATORY(BCS306A)
}

public boolean isEmpty() {


return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}

public int size() {


return top + 1;
}

public void printStack() {


for (int i = 0; i <= top; i++) {
[Link](stack[i] + " ");
}
[Link]();
}

public static void main(String[] args) {


// Create a stack with a maximum size of 10 integers
Stack_Operations stack = new Stack_Operations(10);
// Push some integers onto the stack
[Link]("Pushing integers onto the stack:");
for (int i = 0; i < 10; i++) {
[Link](i);
}
// Print the stack
[Link]("Stack after pushing:");
[Link]();
// Pop some integers off the stack
[Link]("Popping integers off the stack:");
for (int i = 0; i < 5; i++) {
[Link](i);
[Link]("Stack after pop:");
[Link]();

Dept. of ISE, JSSATEB Page:10


OOP WITH JAVA LABOTRATORY(BCS306A)
}
}
}
}

OUTPUT:

0123456789
Popping integers off the stack:
Stack after pop:
012345678
Stack after pop:
01234567
Stack after pop:
0123456
Stack after pop:
012345
Stack after pop:
012340123456789
Popping integers off the stack:
Stack after pop:
012345678
Stack after pop:
01234567
Stack after pop:
0123456
Stack after pop:
012345
Stack after pop:
01234

Dept. of ISE, JSSATEB Page:10


OOP WITH JAVA LABOTRATORY(BCS306A)
Program 3:
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.

Aim: Demonstrating creation of java classes, object, declaration and initializationof v


variables.

public class Employee_Sal_Inc {


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

public Employee_Sal_Inc(int id, String name, int salary) {


[Link] = id;
[Link] = name;
[Link] = salary;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}

public void raiseSalary(double percent) {


double increase = salary * percent / 100;
salary += increase;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)
", name='" + name + '\'' +
", salary=" + salary +
'}';
}

public static void main(String[] args) {


Employee_Sal_Inc employee = new Employee_Sal_Inc(1, "John Doe", 50000);
[Link]("Employee before salary increase:\n " + employee);
[Link]("Enter how much percent increment you want to give to employee:");
Scanner sc=new Scanner([Link]);
double i=[Link]();

[Link](i);
[Link]("Employee after salary increase: \n" + employee);
}
}

OUTPUT :

Employee before salary increase:


Employee{id=1, name='John Doe', salary=50000.0}
Enter how much percent increment you want to give to employee:
15
Employee after salary increase:
Employee{id=1, name='John Doe', salary=57500.0

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)

Program 4:
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.
Aim: Demonstrating creation of java classes, object, declaration and initializationof
variables.

public class My_Point1 {


public class MyPoint {

}
private int x;
private int y;
public My_Point1(int i, int j) {
this.x = x;
this.y = y;
}

public My_Point1() {
this(0, 0);
}

public void setXY(int x, int y) {

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)
this.x = x;
this.y = y;

}
public int[] getXY() {
int[] xy = new int[2];
xy[0] = x;
xy[1] = y;
return xy;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public double distance(int x, int y) {
return [Link]([Link](this.x - x, 2) + [Link](this.y - y, 2));
}
public double distance(My_Point1 another) {
return [Link]([Link](this.x - another, 2) + [Link](this.y - another, 2));
}
public double distance() {
return [Link]([Link](this.x , 2) + [Link](this.y , 2));
}

public static void main(String[] args) {


My_Point1 p1 = new My_Point1();
[Link](p1);
My_Point1 p2 = new My_Point1(3, 4);
[Link](p2);
[Link](5, 6);
[Link](p1);
int[] xy = [Link]();
[Link](xy[0]);
[Link](xy[1]);
[Link]([Link](2, 3));
[Link]([Link](p2));
[Link]([Link]());
}
}

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)
Program: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.
Aim: Demonstrate the core object-oriented concept of inheritance and polymorphism
public abstract class Shape {
private String name;
public Shape(String name) {
[Link] = name;
}
public String getName() {
return name;
}
public abstract double calculateArea();
public abstract double calculatePerimeter();

public static void main(String[] args) {


Shape circle = new Circle("Circle", 5.0);
[Link]("Area of circle: " + [Link]());
[Link]("Perimeter of circle: " + [Link]());
Shape triangle = new Triangle("Triangle", 3.0, 4.0, 5.0);
[Link]("Area of triangle: " + [Link]());
[Link]("Perimeter of Triangle"+ [Link]());
}

public class Circle extends Shape{


private double radius;
public Circle(String name, double radius) {
super(name);
[Link] = radius;
}
@Override
public double calculateArea() {
return [Link] * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * [Link] * radius;

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)
}
}

public class Triangle extends Shape {


private double sideA;
private double sideB;
private double sideC;
public Triangle(String name, double sideA, double sideB, double sideC) {
super(name);
[Link] = sideA;
[Link] = sideB;
[Link] = sideC;
}
public double calculateArea() {
double semiperimeter = (sideA + sideB + sideC) / 2;
return [Link](semiperimeter * (semiperimeter - sideA) * (semiperimeter - sideB) *
(semiperimeter - sideC));
}
public double calculatePerimeter() {
return sideA + sideB + sideC;
}
}
}

OUTPUT :

Area of circle: 78.53981633974483


Perimeter of circle: 31.41592653589793
Area of triangle: 6.0
Perimeter of Triangle12.0

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)

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.
Aim: Demonstrate constructor and method overloading in java programming.

public abstract class Shape {


private String name;
public Shape(String name) {
[Link] = name;
}
public String getName() {
return name;
}
public abstract double calculateArea();
public abstract double calculatePerimeter();

public static void main(String[] args) {


double i,j,k,l;
[Link]("Enter Radius of circle:");
Scanner sc=new Scanner([Link]);
i=[Link]();
Shape circle = new Circle("Circle",+ i);
[Link]("Area of circle: " + [Link]());
[Link]("Perimeter of circle: " + [Link]());
[Link]("Enter sides of Triangle j, k, l:");
j=[Link]();
k=[Link]();
l=[Link]();
Shape triangle = new Triangle("Triangle", +j , + k, + l);
[Link]("Area of triangle: " + [Link]());
[Link]("Perimeter of Triangle:"+ [Link]());
}

public class Circle extends Shape{


private double i;//radius is declared as variable i
public Circle(String name, double i) {
super(name);
this.i = i;
}

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)
@Override
public double calculateArea() {
return [Link] * i * i;
}
@Override
public double calculatePerimeter() {
return 2 * [Link] * i;
}
}

public class Triangle extends Shape {


private double sideA;
private double sideB;
private double sideC;
public Triangle(String name, double sideA, double sideB, double sideC) {
super(name);
[Link] = sideA;
[Link] = sideB;
[Link] = sideC;
}

public double calculateArea() {


double semiperimeter = (sideA + sideB + sideC) / 2;
return [Link](semiperimeter * (semiperimeter - sideA) * (semiperimeter - sideB) *
(semiperimeter - sideC));
}

public double calculatePerimeter() {


return sideA + sideB + sideC;
}
}

}
OUTPUT:
1. Enter Radius of circle:

6
Area of circle: 113.09733552923255
Perimeter of circle: 37.69911184307752
Enter sides of Triangle j, k, l:
2
3
2
Area of triangle: 1.984313483298443
Perimeter of Triangle:7.0

Dept. of ISE, JSSATEB Page:12


OOP WITH JAVA LABOTRATORY(BCS306A)

2. Enter Radius of circle:


4
Area of circle: 50.26548245743669
Perimeter of circle: 25.132741228718345
Enter sides of Triangle j, k, l:
5
4
2
Area of triangle: 3.799671038392666
PerimeterofTriangle:11.0

Dept. of ISE, JSSATEB Page:20


OOP WITH JAVA LABOTRATORY(BCS306A)

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

Aim: Demonstrate the use of packages in java programming.

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

class Rectangle implements Resizable {


private int width;
private int height;
public Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}
@Override
public void resizeWidth(int width) {
[Link] = width;
}
@Override
public void resizeHeight(int height) {
[Link] = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 20);
[Link]("Original width: " + [Link]());
[Link]("Original height: " + [Link]());
[Link](30);
[Link](40);
[Link]("New width: " + [Link]());
[Link]("New height: " + [Link]());
}
}

Dept. of ISE, JSSATEB Page:20


OOP WITH JAVA LABOTRATORY(BCS306A)

OUTPUT:
Original width: 10
Original height: 20
New width: 30
New height: 40

Dept. of ISE, JSSATEB Page:20


OOP WITH JAVA LABOTRATORY(BCS306A)

Program:8
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.

Aim: Demonstrate the inheritance along with interface in java programming.

public class Outer_Inner {

public void display() {


[Link]("Outer class display method");

class Inner {
public void display() {
[Link]("Inner class display method");
}
}
}

public static void main(String[] args) {


Outer_Inner outer = new Outer_Inner();
[Link]();
Outer_Inner.Inner inner = [Link] Inner();
[Link]();
}
}

OUTPUT

Outer class display method


Inner class display method

[Link] ISE, JSSATEB Page:23


OOP WITH JAVA LABOTRATORY(BCS306A)

Program:9
Develop a JAVA program to raise a custom exception (user defined exception) for Division
By Zero using try, catch, throw and finally

Aim: Demonstrate creation of user defined exception

import [Link];

public class Custom_Exception {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter two numbers: ");
int a = [Link]();
int b = [Link]();
try {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed!");
}

float result = a / b;
[Link]("Result: " + result);
}
catch (ArithmeticException e)
{
[Link]([Link]());
} finally {
[Link]();

}
}
OUTPUT:
Enter two numbers:
10
2
Result: 5.0
Enter two numbers:
10
0
Division by zero is not allowed!

[Link] ISE, JSSATEB Page:23


OOP WITH JAVA LABOTRATORY(BCS306A)

Program:10.
Develop a JAVA program to create a package named mypack and import & implement it
in a suitable class.

Aim: Demonstrate the IO Package using java programming.

public class MyClass implements Mypackage_interface {


public void display() {
[Link]("Hello from MyClass!");
}

public interface Mypackage_interface {


void display();
}

public static void main(String[] args) {


MyClass obj = new MyClass();
[Link]();
}

OUTPUT:

Hello from MyClass!

Dept. of ISE, JSSATEB Page:25


OOP WITH JAVA LABOTRATORY(BCS306A)
Program:11.
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).

Aim: Exception handling in java, introduction to throwable class, throw, finally.

public class Thread_Example implements Runnable {

private String name;


public Thread_Example(String name) {
[Link] = name;
}
@Override
public void run() {
[Link]("Thread started: " + name);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]();
}
[Link]("Thread ended: " + name);
}

public static void main(String[] args) {


Thread_Example runnableExample1 = new Thread_Example("Thread-1");
Thread_Example runnableExample2 = new Thread_Example("Thread-2");
Thread_Example runnableExample3 = new Thread_Example("Thread-3");
Thread thread1 = new Thread(runnableExample1);
Thread thread2 = new Thread(runnableExample2);
Thread thread3 = new Thread(runnableExample3);
[Link]();
[Link]();
[Link]();
}
}
OUTPUT 1:
Thread started: Thread-1
Thread started: Thread-2
Thread started: Thread-3
Thread ended: Thread-1
Thread ended: Thread-2
Thread ended: Thread-3

[Link] ISE, JSSATEB Page:26


OOP WITH JAVA LABOTRATORY(BCS306A)
Program:12
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.
Aim: Demonstrate the file operations in java programming.
public class MyThread extends Thread {
public MyThread() {
super();
[Link]("Child Thread");
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
[Link]("Child Thread: " + i);
[Link](500);
}
} catch (InterruptedException e) {
[Link]();
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
[Link]();
try {
for (int i = 0; i < 5; i++) {
[Link]("Main Thread: " + i);
[Link](500);
}
} catch (InterruptedException e) {
[Link]();
}
}
}
OUTPUT1:
Child Thread
Main Thread: 0
Child Thread: 0
Child Thread: 1
Main Thread: 1
Child Thread: 2
Main Thread: 2
Child Thread: 3
Main Thread: 3
Child Thread: 4 Main Thread: 4

Dept. of ISE, JSSATEB Page:30

Common questions

Powered by AI

The use of generic methods in stack operations allows for type safety and reusability without sacrificing type-checking at compile time. By allowing a stack to handle any object type, the operations to push, pop, or peek can work on any data type while ensuring that operations performed are type-safe and errors are caught early during compilation. This flexibility improves a program's ability to handle data elegantly and reduces the overhead of casting and errors during runtime, supporting robust and reusable code design.

The raiseSalary(double percent) method in the Employee class increases the employee's current salary by a given percentage. It calculates the increase by multiplying the current salary by the percentage divided by 100, and then adds the result to the existing salary. This illustrates encapsulation, as the method provides a controlled way to modify the salary attribute while keeping it private and hidden from direct external modifications. This promotes data integrity and security.

The use of interfaces like Resizable in Java allows different classes to share a contract to implement certain methods without needing to share an inheritance chain. The Rectangle class implements the Resizable interface, providing concrete definitions for resizeWidth() and resizeHeight(). This signifies decoupling between what actions can be performed on an object and the object's specific class hierarchy, supporting flexible polymorphism and design patterns like Strategy or Observer. Interfaces enable multiple inheritance scenarios, allowing a class to conform to multiple types.

Polymorphism is demonstrated through the use of an abstract class, Shape, and its subclasses Circle and Triangle. The Shape class defines the abstract methods calculateArea() and calculatePerimeter(), which are implemented by both Circle and Triangle. When instances of these subclasses are called to execute these methods, the method implementation specific to the object's class is invoked, exhibiting polymorphism. For example, when calculateArea() is called on a Circle object, the Circle's version is executed, and similarly for Triangle. This allows objects to be treated as their superclass type while exhibiting behavior specific to their subclass.

The MyThread class demonstrates Java's multithreading capabilities, showing how threads can be created and executed concurrently. The class extends Thread and overrides the run() method, which includes logic that runs in separate threads. It illustrates the use of the Thread class for thread creation, and the sleep() method to pause a thread temporarily. Both main and child threads run concurrently, showing the transition from single-threaded to multi-threaded applications where tasks can be performed simultaneously, improving application efficiency and responsiveness.

Synchronization in Java can enhance thread safety by ensuring that only one thread can access a resource at any given point in time. In the runnable class example, threads run independently but could potentially access shared resources or modify shared data concurrently, leading to inconsistencies. By synchronizing critical sections of code, such as methods that alter shared variables, Java can prevent concurrent access issues. Synchronization can be achieved using synchronized blocks or methods, ensuring reliable data handling and preventing race conditions in multithreaded environments.

Encapsulation contributes to data integrity in the Employee class by restricting direct access to the fields (id, name, and salary) using private access modifiers. Instead, it provides public getter and setter methods, such as getId(), getName(), and getSalary(), which allow controlled access to the field values. This approach ensures that class internals are hidden from external access and modifications, reducing the risk of unintended data corruption and enforcing rules for modifying the object's state, such as through the raiseSalary method.

In Java, a custom exception for division by zero is raised using a try-catch block. The program takes two integer inputs. If the divisor is zero, an ArithmeticException is thrown explicitly with a message indicating that division by zero is not allowed. The catch block catches this exception and prints the error message. The finally block ensures that resources like Scanner are closed, regardless of whether an exception occurs. This mechanism ensures safe error-handling and appropriate resource management.

Inheritance is showcased through the nested classes where a public class Outer_Inner contains another class named Inner. Although this does not illustrate classical inheritance where subclasses extend parent classes, it demonstrates how an inner class can inherit the context of its outer class. The inner class can access private members of the outer class and vice versa, which facilitates data hiding and encapsulation. This approach supports encapsulating helper classes and logic, reducing the scope of helper classes to within the usage context.

The draw() and erase() methods in the Shape subclasses (Circle, Triangle, and Square) demonstrate polymorphism through overriding and method specialization. Each subclass must define its own versions of these methods, allowing the method execution to vary depending on the object's actual type at runtime. When a Shape reference is used to store an object of any subclass like Circle or Triangle, the respective draw() or erase() method implementation is called, according to the actual object type, rather than the reference type, underscoring polymorphism.

You might also like