BCS306A Lab-Manual - Final
BCS306A Lab-Manual - Final
LAB MANUAL
Prepared By
Mamatha C R
Asso. Professor
Dept. of CSE(DS)
Vision and Mission of the Institute
Vision
To become a leading institute for quality technical education and research with ethical values.
Mission
M1: To continually improve quality education system that produces thinking engineers having
good technical capabilities with human values.
M2: To nurture a good eco-system that encourages faculty and students to engage in meaningful
research and development.
M3: To strengthen industry institute interface for promoting team work, internship and
entrepreneurship.
M4: To enhance educational opportunities to the rural and weaker sections of the society to equip
with practical skills to face the challenges of life.
Mission
M1: To nurture a positive environment with state of art facilities conducive for deep learning
and meaningful research and development.
M2: To enhance interaction with industry for promoting collaborative research in emerging
technologies.
M3: To strengthen the learning experiences enabling the students to become ethical professionals
with good interpersonal skills, capable of working effectively in multi-disciplinary teams.
PROGRAM EDUCATIONAL OBJECTIVES (PEOS)
PEO 1: Successful and ethical professionals in IT and ITES industries contributing to societal
progress.
PEO 2: Engaged in life-long learning, adapting to changing technological scenarios.
PEO 3: Communicate and work effectively in diverse teams and exhibit leadership qualities.
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
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.
4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
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.
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.
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
10. Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
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).
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.
Table of contents
Exp Experiments Page
. No.
No.
1
10
11
12
OOPS with Java Laboratory 2024-25
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).
import java.util.Scanner;
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]);
// Check if N is a positive integer
if (N <= 0) {
System.out.println("Please provide a valid positive integer for the order N.");
return;
}
// Create two matrices of order N
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
System.out.println("Matrix 1");
fillMatrix(matrix1);
System.out.println("Matrix 2");
fillMatrix(matrix2);
// Print the matrices
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("\nMatrix 2:");
printMatrix(matrix2);
// Add the matrices
}
System.out.println();
}
}
}
[sample program]
package chitra;
matrix1[1][0]=1 matrix2[1][0]=1
matrix1[1][1]=2 matrix2[1][1]=2
Sum of matrices is:
0 2
2 4
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.
import java.util.Scanner;
public class Stack {
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
public void push(int value) {
if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}
public void display() {
if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = top; i >= 0; --i) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 9
Pushed: 9
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 8
Pushed: 8
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 7
Pushed: 7
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 1
Enter the value to push: 6
Pushed: 6
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 4
Stack Contents: 6 7 8 9
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 3
Peeked: 6
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 6
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 7
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 8
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Popped: 9
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 2
Stack Underflow! Cannot pop from an empty stack.
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display Stack Contents
0. Exit
Enter your choice: 0
Exiting the program. Goodbye!
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.
import java.util.Scanner;
public class Emloyee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public void display() {
System.out.println("Id: " + id);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
public void raiseSalary(double percentage) {
salary = salary + (salary * percentage / 100);
}
public static void main(String[] args) {
int id;
String name;
double salary, percentage;
Output
Enter Employee Id
200
Enter Employee Name
Gopal
Enter Salary
100000
Employee Details
Id: 200
Name: Gopal
Salary: 100000.0
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.
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
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.
// Base class representing a general Shape
class Shape {
protected String name; // Name of the shape
// Constructor that initializes the name, base, and height of the triangle
public Triangle(String name, double base, double height) {
super(name); // Call to the superclass constructor
this.base = base; // Initialize base
this.height = height; // Initialize height
}
// Constructor that initializes the name and side length of the square
public Square(String name, double side) {
super(name); // Call to the superclass constructor
this.side = side; // Initialize side length
// Loop through each shape and call draw and erase methods
for (Shape shape : shapes) {
shape.draw(); // Draw the shape
shape.erase(); // Erase the shape
System.out.println(); // Print a blank line for better readability
}
}
}
Output:
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
Program 06
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.
// Override method to calculate the area of the triangle using Heron's formula
@Override
public double calculateArea() {
double s = (side1 + side2 + side3) / 2; // Semi-perimeter
Program 07
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.
// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
@Override
public void resizeHeight(int height) {
this.height = height;
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.
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
Program 9
Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
// Custom exception class
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
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
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;
Output:
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
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).
class MyRunnable implements Runnable {
@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
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.
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++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}
// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}
Output
main Thread Count: 1
Child Thread Count: 1
Child Thread Count: 2
main Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
Child Thread Count: 4
main Thread Count: 4
Child Thread Count: 5
main Thread Count: 5