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

Java BCS306A LabManual

Uploaded by

nsshreyas1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views21 pages

Java BCS306A LabManual

Uploaded by

nsshreyas1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

Program 01: Matrix Addition

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;

class Matrix {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of matrices (n):");

int n = sc.nextInt();

int i, j;

int A[][] = new int[n][n];

int B[][] = new int[n][n];

int C[][] = new int[n][n];

System.out.println("Enter the elements into matrix A:");

for (i = 0; i < n; i++) {

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

A[i][j] = sc.nextInt();

System.out.println("Enter the elements into matrix B:");

for (i = 0; i < n; i++) {

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

B[i][j] = sc.nextInt();

for (i = 0; i < n; i++) {

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

C[i][j] = A[i][j] + B[i][j];

System.out.println("Elements of matrix C:");

for (i = 0; i < n; i++) {


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

System.out.print(C[i][j] + " ");

System.out.println();

---------OUTPUT---------

Enter the size of matrices (n):

Enter the elements into matrix A:

Enter the elements into matrix B:

Elements of matrix C:

24

68
Program 02: Stack Operations
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 {

int top = -1;

int capacity = 20;

int[] a = new int[capacity];

void push(int x) {

if (top == capacity - 1) {

System.out.println("Stack is overflow");

System.exit(1);

System.out.println("Inserted element=" + x);

a[++top] = x;

int pop() {

if (top == -1) {

System.out.println("Stack is empty");

System.exit(1);

return a[top--];

public static void main(String[] args) {

Stack s = new Stack();

s.push(10);

s.push(20);

s.push(30);

s.push(40);

s.push(50);

s.push(60);

System.out.println("Popped Element: " + s.pop());

System.out.print("Remaining stack elements: ");


for (int i = 0; i <= s.top; i++) {

System.out.print(s.a[i] + " ");

------------OUTPUT-----------

Inserted element=10

Inserted element=20

Inserted element=30

Inserted element=40

Inserted element=50

Inserted element=60

Popped Element: 60

Remaining stack elements: 0 10 20 30 40 50


Program 03: Employee Class
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

import java.util.Scanner;

class Employee {

int id;

String name;

float salary;

float raiseSalary(float percent) {

return salary + (salary * (percent / 100));

public class Emp {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Employee e = new Employee();

e.id = 1;

e.name = "MNS";

e.salary = 90000;

System.out.print("Enter the percentage increment: ");

float percent = sc.nextFloat();

System.out.println("Salary after Increment = " + e.raiseSalary(percent));

---------OUTPUT----------

Enter the percentage increment: 10

Salary after Increment = 99000.0


Program 04: 2D Point Class
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
1)Two instance variables x (int) and y (int).
2)A default (or “no-arg”) constructor that construct a point at the default location of (0, 0).
3)A overloaded constructor that constructs a point with the given x and y coordinates.
4) A method setXY() to set both x and y.
5)A method getXY() which returns the x and y in a 2-element int array.
4)A toString() method that returns a string description of the instance in the format “(x, y)”.
5)A method called distance(int x, int y) that returns the distance from this point to another point
at the given (x, y) coordinates
6)An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
7)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, y;

MyPoint() {

this.x = 0;

this.y = 0;

MyPoint(int x, int y) {

this.x = x;

this.y = y;

void setxy(int x, int y) {

this.x = x;

this.y = y;

int[] getxy() {

int[] coordinates = {x, y};

return coordinates;

public String toString() {

return "(" + x + "," + y + ")";

}
double distance(int x, int y) {

int diffx = this.x - x;

int diffy = this.y - y;

return Math.sqrt(diffx * diffx + diffy * diffy);

double distance(MyPoint another) {

return distance(another.x, another.y);

double distance() {

return distance(0, 0);

class TestMyPoint {

public static void main(String args[]) {

MyPoint Point1 = new MyPoint();

MyPoint Point2 = new MyPoint(1, 2);

Point1.setxy(3, 4);

System.out.println("Point 1: " + Point1);

System.out.println("Point 2: " + Point2.getxy()[0] + ", " + Point2.getxy()[1]);

System.out.println("Distance between Point 1 and Point 2: " + Point1.distance(Point2));

System.out.println("Distance between Point 1 and origin(0,0): " + Point1.distance());

----------OUTPUT---------

Point 1: (3,4)

Point 2: 1, 2

Distance between Point 1 and Point 2: 2.8284271247461903

Distance between Point 1 and origin(0,0): 5.0


Program 05: Inheritance & Polymorphism – Shape Class
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 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() {

System.out.println("Erasing square");
}

public class Demo {

public static void main(String[] args) {

Circle c = new Circle();

Triangle t = new Triangle();

Square 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
Program 06: Abstract Class
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

abstract class Shape {

abstract double calculateArea();

abstract double calculatePerimeter();

class Circle extends Shape {

double radius = 5;

double calculateArea() {

return 3.14 * radius * radius;

double calculatePerimeter() {

return 2 * 3.14 * radius;

class Triangle extends Shape {

double a = 3, b = 4, c = 5;

double calculateArea() {

double s = (a + b + c) / 2;

return Math.sqrt(s * (s - a) * (s - b) * (s - c));

double calculatePerimeter() {

return a + b + c;

class Program {

public static void main(String[] args) {

Circle C = new Circle();

Triangle T = new Triangle();

System.out.println("Area of the circle is: " + C.calculateArea());


System.out.println("Perimeter of the circle is: " + C.calculatePerimeter());

System.out.println("Area of the triangle is: " + T.calculateArea());

System.out.println("Perimeter of the triangle is: " + T.calculatePerimeter());

----------OUTPUT---------

Area of the circle is: 78.5

Perimeter of the circle is: 31.400000000000002

Area of the triangle is: 6.0

Perimeter of the triangle is: 12.0


Program 07: Resizable interface
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.

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) {

this.width = width;

this.height = height;

@Override

public void resizeWidth(int width) {

this.width = width;

System.out.println("Resized width to: " + width);

@Override

public void resizeHeight(int height) {

this.height = height;

System.out.println("Resized height to: " + height);


}

public int getWidth() {

return width;

public int getHeight() {

return height;

public void displayInfo() {

System.out.println("Rectangle: Width = " + width + ", Height = " + height);

public class ResizeDemo {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle(10, 5);

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

rectangle.displayInfo();

rectangle.resizeWidth(15);

rectangle.resizeHeight(8);

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
Updated Rectangle Info:
Rectangle: Width = 15, Height = 8

Program 08: Outer class


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 OuterInnerDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.display();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

-------OUTPUT---------

Outer class display method


Inner class display method
Program 09: Custom Exception
Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

class DivisionByZeroException extends Exception {

public DivisionByZeroException(String message) {

super(message);

public class CustomExceptionDemo {

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

-------OUTPUT--------

Exception caught: Cannot divide by zero!


Finally block executed

Program 10: Packages


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!");

// New utility method

public static int addNumbers(int a, int b) {

return a + b;

Now, let’s create the main program in a different file outside the mypack folder:

// Main program outside the mypack folder


import mypack.MyPackageClass;

public class PackageDemo {

public static void main(String[] args) {

MyPackageClass myPackageObject = new MyPackageClass();

myPackageObject.displayMessage();

int result = MyPackageClass.addNumbers(5, 3);

System.out.println("Result of adding numbers: " + result);

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

Step 1: Organize your directory structure as follows:

project-directory/

├── mypack/

│ └── MyPackageClass.java

└── PackageDemo.java

Step 2: Compile the files:

javac mypack/MyPackageClass.java

javac PackageDemo.java

--------OUTPUT---------

Hello from MyPackageClass in mypack package!

Result of adding numbers: 8

Program 11: Runnable Interface


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 {

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 RunnableThreadExample {

public static void main(String[] args) {

MyRunnable myRunnable1 = new MyRunnable();

MyRunnable myRunnable2 = new MyRunnable();

MyRunnable myRunnable3 = new MyRunnable();

MyRunnable myRunnable4 = new MyRunnable();


MyRunnable myRunnable5 = new MyRunnable();

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);

thread1.start();

thread2.start();

thread3.start();

thread4.start();

thread5.start();

try {

Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

myRunnable1.stopThread();

myRunnable2.stopThread();

myRunnable3.stopThread();

myRunnable4.stopThread();

myRunnable5.stopThread();

-------OUTPUT--------
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.
Program 12: Thread Class
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 {

public MyThread(String name) {

super(name);

start();

@Override

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(Thread.currentThread().getName() + " Count: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " Thread interrupted.");

}
public class ThreadConcurrentExample {

public static void main(String[] args) {

MyThread myThread = new MyThread("Child Thread");

for (int i = 1; i <= 5; i++) {

System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " Thread interrupted.");

--------OUTPUT--------

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

You might also like