0% found this document useful (0 votes)
4 views

JAVA Lab Record (1)

The document contains multiple Java lab programs demonstrating various programming concepts. It includes programs for matrix addition, stack operations, employee salary management, 2D point modeling, shape polymorphism, abstract classes for shape calculations, and interface implementation for resizing shapes. Each program is accompanied by code snippets and descriptions of their functionality.

Uploaded by

patilchinmay510
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JAVA Lab Record (1)

The document contains multiple Java lab programs demonstrating various programming concepts. It includes programs for matrix addition, stack operations, employee salary management, 2D point modeling, shape polymorphism, abstract classes for shape calculations, and interface implementation for resizing shapes. Each program is accompanied by code snippets and descriptions of their functionality.

Uploaded by

patilchinmay510
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

LAB PROGRAM 1

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

PROGRAM -

public class MatrixAddition


{
public static void main(String[] args)
{
// Check if the number of command line arguments is correct
if (args.length != 1)
{
System.out.println("Usage: java MatrixAddition <order N>");
return;
}
// Parse the command line argument to get the order 'N'
int N = Integer.parseInt(args[0]);

// Initialize matrices
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
int[][] result = new int[N][N];

// Input for the first matrix


System.out.println("Enter elements for Matrix 1:");
inputMatrix(matrix1);

// Input for the second matrix


System.out.println("Enter elements for Matrix 2:");
inputMatrix(matrix2);

// Perform matrix addition


addMatrices(matrix1, matrix2, result);

// Display the result


System.out.println("Resultant Matrix after Addition:");
displayMatrix(result);
}

// Function to input elements of a matrix


public static void inputMatrix(int[][] matrix)
{
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++);
{
System.out.print("Enter element at position (" + i + ", " + j + "): ");
matrix[i][j] = scanner.nextInt();
}

1 / 25
}
}

// Function to add two matrices


public static void addMatrices(int[][] matrix1, int[][] matrix2, int[][] result)
{
for (int i = 0; i < matrix1.length; i++)
{
for (int j = 0; j < matrix1[0].length; j++)
{
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to display a matrix


public static void displayMatrix(int[][] matrix)
{
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}

OUTPUT -

2 / 25
LAB PROGRAM 2

(Q2) Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack Operations.

PROGRAM -

public class Stack


{
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;

// Constructor
public Stack()
{
stackArray = new int[MAX_SIZE];
top = -1;
}

// Method to push an element onto the stack


public void push(int element)
{
if (top < MAX_SIZE - 1)
{
stackArray[++top] = element;
System.out.println("Pushed: " + element);
}
else
{
System.out.println("Stack Overflow! Cannot push " + element);
}
}

// Method to pop an element from the stack


public void pop()
{
if (top >= 0)
{
int poppedElement = stackArray[top--];
System.out.println("Popped: " + poppedElement);
}
else
{
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
}
}

// Method to display the elements in the stack


public void display()
{
if (top >= 0)

3 / 25
{
System.out.println("Elements in the Stack:");

for (int i = top; i >= 0; i--)


{
System.out.println(stackArray[i]);
}
}
else
{
System.out.println("Stack is empty.");
}
}

public static void main(String[] args)


{
// Create a stack
Stack myStack = new Stack();

// Perform stack operations


myStack.push(60);
myStack.push(50);
myStack.push(40);
myStack.display();
myStack.pop();
myStack.display();
myStack.push(30);
myStack.push(20);
myStack.push(10);
myStack.display();
myStack.pop();
myStack.pop();
myStack.display();
}
}

4 / 25
OUTPUT -

5 / 25
LAB PROGRAM 3

(Q3) 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.

PROGRAM -

public class Employee


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

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

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

public String getName()


{
return name;
}

public double getSalary()


{
return salary;
}

// Method to raise the salary by a given percentage


public void raiseSalary(double percent)
{
if (percent > 0)
{
double increaseAmount = salary * (percent / 100);
salary += increaseAmount;
System.out.println("Salary raised by " + percent + "%. New salary: $" +
salary);
}
else
{
System.out.println("Invalid percentage. Salary remains unchanged.");
}

6 / 25
}

public static void main(String[] args)


{
// Create an Employee object
Employee employee1 = new Employee(101, "John Doe", 50000.0);

// Display initial details


System.out.println("Employee details before raise:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " + employee1.getName());
System.out.println("Salary: $" + employee1.getSalary());

// Raise the salary by 10%


employee1.raiseSalary(10);

// Display details after the raise


System.out.println("\nEmployee details after raise:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " + employee1.getName());
System.out.println("Salary: $" + employee1.getSalary());
}
}

OUTPUT -

7 / 25
LAB PROGRAM 4

(Q4) Program: 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 construct 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 that
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 diatance 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.

PROGRAM -

class MyPoint
{
private int x;
private int y;

// Default constructor
public MyPoint()
{
this.x = 0;
this.y = 0;
}

// Overloaded constructor
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}

// Method to set both x and y


public void setXY(int x, int y)
{
this.x = x;
this.y = y;
}

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

8 / 25
public int[] getXY()
{

return new int[]{x, y};


}

// Method to get a string description of the instance @Override


public String toString()
{
return "(" + x + ", " + y + ")";
}

// Method to calculate the distance to another point at (x, y)


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

// Overloaded method to calculate the distance to another MyPoint


public double distance(MyPoint another)
{
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}

// Another overloaded method to calculate the distance to the origin (0, 0)


public double distance()
{
return Math.sqrt(x * x + y * y);
}
}

public class TestMyPoint


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

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

// Set new coordinates for point1


point1.setXY(1, 2);

// Display updated point1


System.out.println("Point 1 (after setXY): " + point1.toString());

9 / 25
// Get coordinates of point1

int[] coordinates = point1.getXY();


System.out.println("Coordinates of Point 1: (" + coordinates[0] + ", " +
coordinates[1] + ")");

// Calculate distance between point1 and point2


double distance1 = point1.distance(point2);
System.out.println("Distance between Point 1 and Point 2: " + distance1);

// Calculate distance of point1 to the origin


double distance2 = point1.distance();
System.out.println("Distance from Point 1 to the Origin: " + distance2);
}
}

OUTPUT -

10 / 25
LAB PROGRAM 5

(Q5) 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 members
data and main program.

PROGRAM -

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

public void erase()


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

class Circle extends Shape


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

// Override erase method for Circle


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

class Triangle extends Shape


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

// Override erase method for Triangle


@Override
public void erase()
{

11 / 25
System.out.println("Erasing a triangle");
}
}
class Square extends Shape
{
// Override draw method for Square
@Override
public void draw()
{
System.out.println("Drawing a square");
}

// Override erase method for Square


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

public class TestShapes


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

// Demonstrate polymorphism
for (Shape shape : shapes)
{
shape.draw();
shape.erase();
System.out.println(); // Add a newline for clarity
}
}
}
OUTPUT -

12 / 25
LAB PROGRAM 6

(Q6) Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeters(). Create subclasses Circle and Triangle that extend
the Shape class and implement the respective methods to calculate the area and perimeters
of each shape.

PROGRAM -

abstract class Shape


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

class Circle extends Shape


{
private double radius;

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

// Implement abstract methods

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

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

class Triangle extends Shape


{
private double side1;
private double side2;
private double side3;

// Constructor
public Triangle(double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;

13 / 25
this.side3 = side3;
}
// Implement abstract methods

@Override
public double calculateArea()
{
// Heron's formula for the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double calculatePerimeter()
{
return side1 + side2 + side3;
}
}

public class TestShapes


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

// Display area and perimeter for Circle


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

// Display area and perimeter for Triangle


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

14 / 25
OUTPUT -

15 / 25
LAB PROGRAM 7

(Q7) 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
implement the Resizable inteeface and implements the resize methods.

PROGRAM -

// Define the Resizable interface


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

// Implement the Resizable interface in the Rectangle class


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

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

// Implement resizeWidth method

@Override
public void resizeWidth(int width)
{
this.width = width;
System.out.println("Width resized to: " + width);
}

// Implement resizeHeight method

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

// Display the current dimensions of the rectangle


public void displayDimensions()
{
System.out.println("Rectangle Dimensions - Width: " + width + ", Height: " +
height);
}

16 / 25
}

public class TestResizable


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

// Display the initial dimensions


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

// Resize the width and height


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

// Display the dimensions after resizing


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

OUTPUT -

17 / 25
LAB PROGRAM 8

(Q8) 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.

PROGRAM -

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

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

public class MainClass


{
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 using the outer class instance
Outer.Inner inner = outer.new Inner();

// Call the display method of the inner class


inner.display();
}
}

OUTPUT -

18 / 25
LAB PROGRAM 9

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

PROGRAM -

// Custom exception class


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

public class CustomExceptionExample


{
public static void main(String[] args)
{
try
{
// Perform division operation that might result in division by zero
int numerator = 10;
int denominator = 0;

// Check if the denominator is zero


if (denominator == 0)
{
throw new DivisionByZeroException("Division by zero is not
allowed");
}
int result = numerator / denominator;
System.out.println("Result of the division: " + result);
}
catch (DivisionByZeroException e)
{
// Handle the custom exception
System.out.println("Error: " + e.getMessage());
}
catch (ArithmeticException e)
{
// Handle the regular ArithmeticException (e.g., if the denominator is zero)
System.out.println("Error: " + e.getMessage());
}
finally
{
// This block is always executed, regardless of whether an exception is thrown
// or not
System.out.println("Finally block executed");
}
}

19 / 25
}

OUTPUT -

20 / 25
LAB PROGRAM 10

(Q10) Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.

PROGRAM -

// Create the mypack package


// Create a directory named mypack. Inside it, create a Java file named MyClass.java
// mypack/MyClass.java (Directory)
package mypack;

public class MyClass


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

// Create a class that imports and uses MyClass:


// Now, create another class in a different directory (let's call it MainClass)
// MainClass.java
import mypack.MyClass;

public class MainClass


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

// Call the displayMessage method from MyClass


myObject.displayMessage();
}
}
// Now, compile and run the MainClass

OUTPUT -

21 / 25
LAB PROGRAM 11

(Q11) 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).

PROGRAM -

class MyRunnable implements Runnable


{
private String threadName;

public MyRunnable(String name)


{
this.threadName = name;
}

@Override
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(threadName + ": Count - " + i);

// Sleep for 500 milliseconds


Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(threadName + " thread interrupted.");
}
System.out.println(threadName + " thread exiting.");
}
}

public class RunnableThreadExample


{
public static void main(String[] args)
{
// Create instances of MyRunnable
MyRunnable runnable1 = new MyRunnable("Thread 1");
MyRunnable runnable2 = new MyRunnable("Thread 2");

// Create threads and associate them with the runnable instances


Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);

// Start the threads

22 / 25
thread1.start();
thread2.start();

// Main thread
for (int i = 1; i <= 5; i++)
{
System.out.println("Main Thread: Count - " + i);
try
{
// Sleep for 500 milliseconds
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
}
System.out.println("Main thread exiting.");
}
}

OUTPUT -

23 / 25
LAB PROGRAM 12

(Q12) 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.

PROGRAM -

class MyThread extends Thread


{
public MyThread(String threadName)
{
// Call the base class constructor
super(threadName);

// Start the thread


start();
}

@Override
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(Thread.currentThread().getName() + ": Count - " +
i);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + " thread
interrupted.");
}
System.out.println(Thread.currentThread().getName() + " thread exiting.");
}
}

public class ThreadExample


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

// Main thread
try
{
for (int i = 1; i <= 5; i++)

24 / 25
{
System.out.println(Thread.currentThread().getName() + ": Count - " +
i);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + " thread
interrupted.");
}
System.out.println(Thread.currentThread().getName() + " thread exiting.");
}
}

OUTPUT -

25 / 25

You might also like