0% found this document useful (0 votes)
30 views29 pages

2022 Java Lab Manual

Uploaded by

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

2022 Java Lab Manual

Uploaded by

starkexpo3k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

1

DEPARTMENT OF COMPUTERSCIENCE AND ENGINEERING

III SEMESTER

ObjectOrientedProgrammingwithJAVA
(BCS306A)

As per Choice Based Credit System (CBCS) scheme

1
2

DEPARTMENT OF COMPUTERSCIENCE AND ENGINEERING

VISION

”To Emanate as a Prime Source of Technical Education In The Field of Engineering”.

MISSION

The Department of Computer Science And Engineering will Provide Transformative


Educationand Research to create, Contribute innovators and Leaders for society and Industry.

III SEMESTER

ObjectOrientedProgrammingwithJAVA
(BCS306A)

As per Choice Based Credit System (CBCS) scheme

Signature of the Faculty Signature of the HOD

2
3

ObjectOrientedProgrammingwithJAVA
(BCS306A)

VTU 3rd SEMESTER


COMPUTERSCIENCEENGINEERING

PREPARED BY
THRIPURAMBHA M P
(TUTOR)
DEPT OF CSE
RRCE,BANGALORE

3
4

LAB CYCLE PROGRAMS

1. Develop a JAVA program to add TWO matrices of suitable order N (The


value of N should be read from command line arguments).
To develop a Java program to add two matrices of suitable order N, you can follow these steps:

 Accept the value of N (order of matrices) from command-line arguments.


 Create two N x N matrices, which you can represent as two-dimensional arrays.
 Initialize the matrices with values, either randomly or by reading input from the user.
 Add the corresponding elements of the two matrices and store the result in a third matrix.
 Display the original matrices and the result matrix.

Here's a Java program

public class MatrixAddition {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the order N as a command line argument.");
return;
}

int N = Integer.parseInt(args[0]);

if (N <= 0) {
System.out.println("Order N should be a positive integer.");
return;
}

// Initialize the matrices


int[][] matrixA = new int[N][N];
int[][] matrixB = new int[N][N];
int[][] resultMatrix = new int[N][N];

// Populate the matrices with values (You can modify this part)
// For simplicity, we'll use a counter to fill the matrices.
int counter = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrixA[i][j] = counter;
matrixB[i][j] = counter * 2;
counter++;
}
}

// Perform matrix addition

4
5

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


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

// Display the matrices


System.out.println("Matrix A:");
printMatrix(matrixA);

System.out.println("Matrix B:");
printMatrix(matrixB);

System.out.println("Result Matrix (A + B):");


printMatrix(resultMatrix);
}

public static void printMatrix(int[][] matrix) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

In this program, we first validate the command-line argument, initialize two matrices with
sample values, perform matrix addition, and then display the original matrices and the result
matrix. You can modify the code to accept user input or generate matrices differently if needed.

5
6

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


methods. Develop a JAVA main method to illustrate Stack operations.

Java program that defines a simple stack class to hold a maximum of 10 integers and provides
methods for stack operations. We will also develop a main method to illustrate stack operations:

public class IntegerStack {


private int maxSize;
private int top;
private int[] stackArray;

public IntegerStack(int maxSize) {


this.maxSize = maxSize;
this.stackArray = new int[maxSize];
this.top = -1; // Initialize the top pointer to -1 (empty stack)
}

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == maxSize - 1;
}

public void push(int value) {


if (isFull()) {
System.out.println("Stack is full. Cannot push " + value);
} else {
stackArray[++top] = value;
System.out.println("Pushed " + value + " onto the stack.");
}
}

public int pop() {


if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Return a sentinel value to indicate an error.
} else {
int poppedValue = stackArray[top--];
System.out.println("Popped " + poppedValue + " from the stack.");
return poppedValue;
}
}

6
7

public int peek() {


if (isEmpty()) {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a sentinel value to indicate an error.
} else {
return stackArray[top];
}
}

public void display() {


System.out.print("Stack (top to bottom): ");
for (int i = top; i >= 0; i--) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


IntegerStack stack = new IntegerStack(10);

stack.push(5);
stack.push(10);
stack.push(15);
stack.display();

int poppedValue = stack.pop();


if (poppedValue != -1) {
System.out.println("Popped value: " + poppedValue);
}

System.out.println("Top of the stack: " + stack.peek());


}
}} }
In this program, we've created a IntegerStack class with methods for common stack operations
like push, pop, peek, isEmpty, and isFull. In the main method, we illustrate these operations by
pushing values onto the stack, popping values, and displaying the stack's contents.

7
8

3. A class called Employee, which models an employee with an ID, name and
salary, is designed as shown inthe following class diagram. The method
raiseSalary (percent) increases the salary by the givenpercentage. Develop the
Employee class and suitable main method for demonstration.

Based on the class diagram you provided, here's a simple implementation of the Employee class
in Java:

public class Employee


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

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


salary += salary * (percent / 100);
System.out.println(name + "'s salary has been increased by " + percent + "%. New salary: "
+ salary);
}

public void display() {


System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: " + salary);
System.out.println();
}

public static void main(String[] args) {


// Creating an Employee object
Employee employee1 = new Employee(1, "John Doe", 50000);

// Displaying initial details


System.out.println("Initial Employee Details:");
employee1.display();

// Raising salary by 10%


employee1.raiseSalary(10);

8
9

// Displaying updated details


System.out.println("Updated Employee Details:");
employee1.display();
}
}
This implementation includes the Employee class with an id, name, and salary fields. The
raiseSalary method increases the salary by the given percentage, and the display method prints
the employee details. The main method demonstrates the creation of an Employee object, initial
display, raising the salary, and displaying the updated details.

9
1

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.

let's start with the implementation of the MyPoint class:


public class MyPoint {
private int x;
private int y;

// Default constructor
public MyPoint() {
x = 0;
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;

1
0
1

this.y = y;
}

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


public int[] getXY() {
return new int[]{x, y};
}

// Method to return a string description of the instance in the format "(x, y)"
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

// Method to calculate distance from this point to another point at given (x, y) coordinates
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 distance from this point to another MyPoint instance
public double distance(MyPoint another) {
return distance(another.x, another.y);
}

// Overloaded method to calculate distance from this point to the origin (0, 0)
public double distance() {
return distance(0, 0);
}
}

Now, let's create a TestMyPoint class to test all the methods defined in the MyPoint class:

public class TestMyPoint {


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

// Testing setXY and getXY methods


point1.setXY(1, 2);
int[] coordinates = point1.getXY();
System.out.println("Point1 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")");

// Testing toString method

1
1
1

System.out.println("Point2: " + point2);

// Testing distance methods


System.out.println("Distance from point1 to (5, 6): " + point1.distance(5, 6));
System.out.println("Distance from point1 to point2: " + point1.distance(point2));
System.out.println("Distance from point2 to origin: " + point2.distance());
}
}

This TestMyPoint class creates instances of MyPoint and tests each of the defined methods.

1
2
1

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.
Sure, let's create the Shape class and its three subclasses Circle, Triangle, and
Square to demonstrate polymorphism:

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

public void erase() {


System.out.println("Erasing the generic shape");
}
}

// Circle class (subclassed from Shape)


class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}

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

// Triangle class (subclassed from Shape)


class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}

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

// Square class (subclassed from Shape)

1
3
1

class Square extends Shape {


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

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

// Main program
public class TestShapes {
public static void main(String[] args) {
// Creating objects of different shapes
Shape genericShape = new Shape();
Circle circle = new Circle();
Triangle triangle = new Triangle();
Square square = new Square();

// Demonstrating polymorphism
drawAndErase(genericShape);
drawAndErase(circle);
drawAndErase(triangle);
drawAndErase(square);
}

// Polymorphic method
public static void drawAndErase(Shape shape) {
shape.draw();
shape.erase();
System.out.println(); // Adding a newline for better readability
}
}

In this example, the Shape class is the base class, and Circle, Triangle, and Square are its
subclasses. Each subclass overrides the draw() and erase() methods to provide specific
implementations for each shape. The TestShapes class demonstrates polymorphism by creating
objects of different shapes and invoking the drawAndErase method with objects of the Shape
type. The actual method called depends on the runtime type of the object, showcasing
polymorphic behavior.

1
4
1

6. Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() andcalculatePerimeter(). Create subclasses Circle and Triangle that extend
the Shape class and implementthe respective methods to calculate the area and perimeter
of each shape.

// Abstract Shape class

abstract class Shape {

// Abstract methods to calculate area and perimeter

public abstract double calculateArea();

public abstract double calculatePerimeter();

// Circle class (subclassed from Shape)

class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double calculateArea() {

return Math.PI * radius * radius;

@Override

1
5
1

public double calculatePerimeter() {

return 2 * Math.PI * radius;

// Triangle class (subclassed from Shape)

class Triangle extends Shape {

private double side1, side2, side3;

public Triangle(double side1, double side2, double side3) {

this.side1 = side1;

this.side2 = side2;

this.side3 = side3;

@Override

public double calculateArea() {

// Using Heron's formula to calculate 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;

1
6
1

// Main program

public class TestShapes {

public static void main(String[] args) {

// Creating objects of Circle and Triangle

Circle circle = new Circle(5);

Triangle triangle = new Triangle(3, 4, 5);

// Calculating and displaying area and perimeter

System.out.println("Circle - Area: " + circle.calculateArea() + ", Perimeter: " +


circle.calculatePerimeter());

System.out.println("Triangle - Area: " + triangle.calculateArea() + ", Perimeter: " +


triangle.calculatePerimeter());

In this program, the Shape class is an abstract class with abstract methods calculateArea() and
calculatePerimeter(). The Circle and Triangle classes extend the Shape class and provide
concrete implementations for these methods to calculate the area and perimeter of a circle and a
triangle, respectively. The TestShapes class demonstrates creating objects of these shapes and
calculating/displaying their area and perimeter.

1
7
1

7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int


width) andresizeHeight(int height) that allow an object to be resized. Create a class
Rectangle that implements theResizable interface and implements the resize methods

Here's a Java program that creates an interface Resizable with methods resizeWidth(int width)
and resizeHeight(int height), and a class Rectangle that implements the Resizable interface and
provides implementations for the resize methods:

// Resizable interface

interface Resizable {

void resizeWidth(int width);

void resizeHeight(int height);

// Rectangle class implementing Resizable interface

class Rectangle implements Resizable {

private int width;

private int height;

public Rectangle(int width, int height) {

this.width = width;

this.height = height;

// Implementation of resizeWidth method

@Override

public void resizeWidth(int width) {

this.width = width;

1
8
1

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

// Implementation of resizeHeight method

@Override

public void resizeHeight(int height) {

this.height = height;

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

// Other methods related to Rectangle class

public void display() {

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

// Main program

public class TestResizable {

public static void main(String[] args) {

// Creating an object of Rectangle

Rectangle rectangle = new Rectangle(10, 20);

// Displaying initial state

System.out.println("Initial Rectangle:");

rectangle.display();

1
9
2

// Resizing width and height

rectangle.resizeWidth(15);

rectangle.resizeHeight(25);

// Displaying final state

System.out.println("Final Rectangle:");

rectangle.display();

In this program, the Resizable interface declares methods resizeWidth(int width) and
resizeHeight(int height). The Rectangle class implements the Resizable interface and provides
concrete implementations for these methods. The TestResizable class demonstrates creating an
object of the Rectangle class, displaying its initial state, resizing its width and height, and then
displaying the final state.

2
0
2

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.

// Outer class

class Outer {

// Outer class function display

void display() {

System.out.println("Outer class display");

// Inner class

class Inner {

// Inner class function display

void display() {

System.out.println("Inner class display");

// Main class

public class Main {

public static void main(String[] args) {

// Create an instance of the outer class

Outer outerObj = new Outer();

2
1
2

// Call the outer class display function

outerObj.display();

// Create an instance of the inner class

Outer.Inner innerObj = outerObj.new Inner();

// Call the inner class display function

innerObj.display();

In this example, the Outer class contains a method named display. Inside the Outer class, there is
an Inner class with its own display method. In the Main class, an instance of the outer class is
created, and its display method is called. Then, an instance of the inner class is created using the
outer class instance (outerObj.new Inner()), and its display method is called.

When you run this program, it should output:

Outer class display

Inner class display

This demonstrates the concept of an outer class containing an inner class, each with its own
display method, and how to call these methods from the main class.

9. Develop a JAVA program to raise a custom exception (user defined


exception) for DivisionByZero using try, catch, throw and finally.

2
2
2

Here's an example of a Java program that raises a custom exception (DivisionByZeroException) for
division by zero using try, catch, throw, and finally:

// Custom exception class


class DivisionByZeroException extends Exception {
// Constructor with a custom error message
public DivisionByZeroException(String message) {
super(message);
}
}

// Main class
public class Main {
public static void main(String[] args) {
try {
// Perform division
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (DivisionByZeroException e) {
// Catch the custom exception and print the error message
System.out.println("Exception caught: " + e.getMessage());
} finally {
// This block will be executed no matter what, whether an exception occurs or not
System.out.println("Finally block executed");
}
}

// Function that may throw a custom exception


static int divide(int numerator, int denominator) throws DivisionByZeroException {
try {
// Try to perform the division
return numerator / denominator;
} catch (ArithmeticException e) {
// Catch the arithmetic exception and throw a custom exception with a meaningful
message
throw new DivisionByZeroException("Division by zero is not allowed.");
}
}
}

In this example:

 The DivisionByZeroException class is a custom exception that extends the Exception


class.

2
3
2

 The divide method attempts to perform division but catches the built-in
ArithmeticException (thrown when dividing by zero) and rethrows it as a
DivisionByZeroException with a custom error message.
 In the main method, we call the divide method, and if a DivisionByZeroException is
thrown, we catch it and print the custom error message. The finally block is executed
regardless of whether an exception occurs or not.
When you run this program and attempt to divide by zero, it will catch the custom exception and
print the error message, and the finally block will be executed.

10. Develop a JAVA program to create a package named mypack and import
& implement it in a suitableclass.

2
4
2

create a package named mypack and import and implement it in a suitable class.
Let's create a simple package with a class in it:
Create a directory named mypack.
Inside the mypack directory, create a file named MyPackageClass.java with the following
content:
// File: mypack/MyPackageClass.java
package mypack;

public class MyPackageClass {


public void displayMessage() {
System.out.println("Hello from MyPackageClass!");
}
}
Now, let's create a class in a different directory that imports and uses the mypack package:
Create a file named MainClass.java with the following content:
// File: MainClass.java

import mypack.MyPackageClass; // Import the MyPackageClass from the mypack package

public class MainClass {


public static void main(String[] args) {
// Create an instance of MyPackageClass
MyPackageClass myPackageObj = new MyPackageClass();

// Call the displayMessage method from MyPackageClass


myPackageObj.displayMessage();
}
}
.java
To compile and run the program:
Open a terminal and navigate to the directory containing the mypack and MainClass files.
Compile the files:
- mypack
- MyPackageClass.java
- MainClass.java.java javac MainClass.java
Run the program:
java MainClass
This should output:
Hello from MyPackageClass!
This example demonstrates the creation of a package named mypack, the definition of a class
(MyPackageClass) within that package, and the import and usage of that class in another class
(MainClass).
Top of Form

2
5
2

11. Write a program to illustrate creation of threads using runnable class.


(start method start each of thenewly created thread. Inside the run method
there is sleep() for suspend the thread for 500milliseconds).
Java program that illustrates the creation of threads using the Runnable interface. Each thread,
when started, will execute the run method, which contains a sleep statement to suspend the
thread for 500 milliseconds.

// Runnable class
class MyRunnable implements Runnable {
@Override
public void run() {
try {
// Print the thread name and ID
System.out.println("Thread " + Thread.currentThread().getName() + " (ID: " +
Thread.currentThread().getId() + ") is running.");

// Suspend the thread for 500 milliseconds


Thread.sleep(500);

// Print a message after waking up


System.out.println("Thread " + Thread.currentThread().getName() + " is awake now.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

// Main class
public class ThreadExample {
public static void main(String[] args) {
// Create two instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();

// Create two threads and pass the instances of MyRunnable to their constructors
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);

// Start the threads


thread1.start();
thread2.start();
}
}

In this example:

2
6
2

 The MyRunnable class implements the Runnable interface and overrides the run method.
 Inside the run method, the thread's name and ID are printed, followed by a sleep
statement that suspends the thread for 500 milliseconds.
 The ThreadExample class creates two instances of MyRunnable, creates two threads, and
starts them using the start method.
When you run this program, you may observe interleaved output from the two threads as they
run concurrently. The sleep statement inside the run method introduces a delay, allowing you to
see how the threads can be suspended for a short period.

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

2
7
2

method of the class starts after this. It can be observed thatboth main thread
and created child thread are executed concurrently.

class MyThread with a constructor, calls the base class constructor using super, and starts the
thread. The run method of the class then executes, demonstrating concurrent execution of the
main thread and the created child thread.
// MyThread class
class MyThread extends Thread {
// Constructor of MyThread class
public MyThread(String threadName) {
// Call the base class (Thread) constructor using super
super(threadName);
}

// Run method of the MyThread class


public void run() {
// Display a message indicating the thread is running
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
}

// Main class
public class ThreadExample {
public static void main(String[] args) {
// Create an instance of MyThread with the name "ChildThread"
MyThread myThread = new MyThread("ChildThread");

// Start the child thread


myThread.start();

// Display a message indicating the main thread is running


System.out.println("Main thread is running.");
}
}
In this example:
 The MyThread class extends the Thread class and has a constructor that takes a thread
name as a parameter. Inside the constructor, it calls the base class (Thread) constructor
using super(threadName).
 The run method of MyThread simply prints a message indicating that the thread is
running.
 In the main method of the ThreadExample class, an instance of MyThread is created with
the name "ChildThread," and then the start method is called to start the thread.
 The main thread also continues to execute, and you'll see concurrent execution messages
from both the main thread and the child thread.
When you run this program, you'll observe that both threads are executing concurrently, and the
output may vary due to the concurrent nature of thread execution.

2
8
2

2
9

You might also like