0% found this document useful (0 votes)
7 views28 pages

Java Laboratory (4)

The document is a Java lab manual for the Department of Computer Science & Engineering at Atria Institute of Technology for the academic year 2023-2024. It outlines various lab experiments, including matrix addition, stack implementation, employee management, point manipulation, shape drawing with polymorphism, abstract class usage, and interface implementation. Each experiment includes a brief description and code examples to demonstrate the concepts being taught.

Uploaded by

abcdabcd12baks
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
7 views28 pages

Java Laboratory (4)

The document is a Java lab manual for the Department of Computer Science & Engineering at Atria Institute of Technology for the academic year 2023-2024. It outlines various lab experiments, including matrix addition, stack implementation, employee management, point manipulation, shape drawing with polymorphism, abstract class usage, and interface implementation. Each experiment includes a brief description and code examples to demonstrate the concepts being taught.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING
Java Lab manual
2023-2024

ATRIA INSTITUTE OF TECHNOLOGY


Adjacent to Bangalore Baptist Hospital
Hebbal Bengaluru-560024
Course Code BCS306 CIE Marks 50
A
Number of Contact Hours/Week 0:0:2 SEE Marks 50
Total Number of Lab Contact Hours 28 Exam Hours 03
Credits-1

Sl Lab Experiments Pg
NO No
PART A
1. Develop a JAVA program to add TWO matrices of suitable order N (The 4
value of N should be read from command line arguments).

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


methods. Develop a JAVA main method to illustrate Stack operations.
3. A class called Employee, which models an employee with an ID, name and 8
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 9
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.
5. Develop a JAVA program to create a class named shape. Create three sub 12
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 14
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
7. Develop a JAVA program to create an interface Resizable with methods 16
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
8. 18
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 20
exception) for DivisionbyZero using try , catch , throw and finally

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

11. Write a program to illustrate creation of threads using runnable class .(start 24
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 26
conmstructor , 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 thread are excecuting concurrently.

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
package java22scheme;
import java.util.Scanner;
public class MatrixAddition {

public static void main(String[] args) {


//Getting the order N of the matrix from command line argument
int order=Integer.parseInt(args[0]);

int a[ ][ ]=new int[order] [order];


int b[ ][ ]=new int[order][order];
int c[ ][ ]=new int[order][order];

Scanner sc = new Scanner(System.in);


//Reading in the elements into matrix a
System.out.println("Enter the elements for matrix a");
for(int i=0;i<order;i++)
{
for(int j=0;j<order;j++)
{
a[i][j]=sc.nextInt();
}
}
//Reading in the elements into matrix b
System.out.println("Enter the elements for matrix b");
for(int i=0;i<order;i++)
{
for(int j=0;j<order;j++)
{
b[i][j]=sc.nextInt();

}
System.out.println("The elements for matrix a");
for(int i=0;i<order;i++)
{
for(int j=0;j<order;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("The elements for matrix b");
for(int i=0;i<order;i++)
{
for(int j=0;j<order;j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println();
}
//Finding the sum
System.out.println("The sum of two matrices is");
for(int i=0;i<order;i++)
{
for(int j=0;j<order;j++)
{
c[i][j]=a[i][j]+b[i][j];

System.out.print(c[i][j]+" ");
}
System.out.println();
}
}

Output:

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


Develop a JAVA main method to illustrate Stack operations.
package java22scheme;
//Stack implementation in Java
public class StackDemo {
// store elements of stack
private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;

// Creating a stack
StackDemo(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}
// push elements to the top of stack
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
// terminates the program
System.exit(1);
}

// insert element on top of stack


System.out.println("Inserting " + x);
arr[++top] = x;
}
// pop elements from top of stack
public int pop() {
// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}
// pop element from top of stack
return arr[top--];
}
// return size of the stack
public int getSize() {
return top + 1;
}
// check if the stack is empty
public Boolean isEmpty() {
return top == -1;
}
// check if the stack is full
public Boolean isFull() {
return top == capacity - 1;}
/ display elements of stack
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args) {
StackDemo stack = new StackDemo(10);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
// remove element from stack
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}

Output:

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.
package java22scheme;
import java.util.Scanner;
public class Employee {
int empid;
String name;
float salary;
public void raisesalary()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the percentage of salary increase");
float percentage=sc.nextInt();
float incrsalary=salary+(salary*(percentage/100));
System.out.println("The salary has increased to "+incrsalary);
}
public static void main(String[] args) {
Employee e1=new Employee();
e1.empid=1001;
e1.name="Harsha";
e1.salary=45000;
e1.raisesalary();
}}
Output:

4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed
as follows:
a. Two instance variables x (int) and y (int).
b. A default (or "no-arg") constructor that construct a point at the default location of (0,
0).
c. A overloaded constructor that constructs a point with the given x and y coordinates.
d. A method setXY() to set both x and y.
e. A method getXY() which returns the x and y in a 2-element int array.
f. A toString() method that returns a string description of the instance in the format "(x,
y)".
g. A method called distance(int x, int y) that returns the distance from this point to
another point at the
given (x, y) coordinates
h. An overloaded distance(MyPoint another) that returns the distance from this point to
the given
MyPoint instance (called another)
i. 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.


package java22scheme;

public class MyPoint {

int x,y;

MyPoint()
{
x=10;
y=10;
}

MyPoint(int x,int y)
{
this.x=x;
this.y=y;
}
public void setXY(int x,int y)
{
this.x=x;
this.y=y;
}
public void getXY()
{
int a[]=new int[2];
a[0]=x;
a[1]=y;

System.out.println("x: "+a[0]+" y: "+a[1]);


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

public void distance(int x, int y)


{
int xDiff = this.x - x;
int yDiff = this.y - y;
System.out.println("The distance between the points ("+x+","+y+")and
("+this.x +","+this.y+") is: "+( Math.sqrt(xDiff*xDiff + yDiff*yDiff)));
}

public void distance(MyPoint another)


{
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
System.out.println("The distance between the points
("+another.x+","+another.y+")and ("+this.x +","+this.y+") is: "+( Math.sqrt(xDiff*xDiff +
yDiff*yDiff))); Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}
public void distance()
{
int xDiff = this.x - 0;
int yDiff = this.y - 0;
System.out.println("The distance between the points ("+x+","+y+")and
origin (0,0) is"+ Math.sqrt(xDiff*xDiff + yDiff*yDiff));

}
package java22scheme;

public class TestMyPoint {


public static void main(String args[])
{
MyPoint mp1=new MyPoint();
System.out.println("The coordinates are: "+mp1);

mp1.distance(15,10);

mp1.distance();

MyPoint mp2=new MyPoint(5,5);


mp2.getXY();

mp2.distance(15,10);
mp2.distance();

MyPoint mp3=new MyPoint();


mp3.setXY(5, 3);
mp3.getXY();

mp3.distance(mp2);
}
}
Output:

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.
package java22scheme;
public class Shape {
public void draw() {
System.out.println("Drawing shape");
}

public void erase() {


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

package java22scheme;

public class Circle extends Shape{


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

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

package java22scheme;

public class Triangle extends Shape{


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

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

package java22scheme;

public class Square extends Shape


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

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

package java22scheme;

public class Main {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Triangle();
Shape shape3 = new Square();

shape1.draw();
shape1.erase();

shape2.draw();
shape2.erase();

shape3.draw();
shape3.erase();
}}

Output:

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.
package java22scheme;
public abstract class Shape {
public abstract double calculateArea();
public abstract double calculatePerimeter();
}
package java22scheme;

public class Circle extends Shape{


private double radius;

public Circle(double radius) {


this.radius = radius;
}

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

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

package java22scheme;

public 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() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

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

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5);
Triangle triangle = new Triangle(3, 4, 5);

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

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

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.
// 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;

public Rectangle(int width, int height)


{
this.width = width;
this.height = height;
}

@Override
public void resizeWidth(int width)
{
if (width > 0)
{
this.width = width;
}
else
{
System.out.println("Invalid width. Width must be greater than 0.");
}
}

@Override
public void resizeHeight(int height)
{
if (height > 0)
{
this.height = height;
}
else
{
System.out.println("Invalid height. Height must be greater than 0.");
}
}

public void display()


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

public class Main


{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle(10, 20);

System.out.println("Original Rectangle:");
rectangle.display();

// Resize the rectangle using the Resizable methods


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

System.out.println("Resized Rectangle:");
rectangle.display();
}
}

Output:

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.
package java22scheme;

public class Outer {


public class Inner {

public void display() {


// TODO Auto-generated method stub

void display() {
System.out.println("Outer display()");
}

package java22scheme;

public class Inner {


// Inner class

void display() {
System.out.println("Inner display()");
}
}

package java22scheme;

public class Main1 {


public static void main(String[] args) {
Outer outerObject = new Outer();
outerObject.display(); // Calls the outer class display()

Outer.Inner innerObject = outerObject.new Inner();


innerObject.display(); // Calls the inner class display()
}
}

Output :
9.Develop a JAVA program to raise a custom exception (user defined exception) for
Division by Zero using try , catch , throw and finally.
package java22scheme;

public class MyException extends Exception{


private String detail;
MyException(String a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}

package java22scheme;

public class ExceptionDemo {


static void compute(int a,int b) throws MyException {
try
{
if(b==0)
throw new MyException("Trying to divide by zero");
else
{
int result=a/b;
System.out.println("The result is: "+result);
}
}
finally
{
System.out.println("In finally block");
}

}
public static void main(String args[]) {
try {
//compute(1,0);
compute(20,5);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

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

public class Calculator {


public int a,b;
public Calculator()
{
a=10;
b=5;
}
public Calculator(int a,int b)
{
this.a=a;
this.b=b;
}
public void sum()
{
System.out.println("The sum is: "+(a+b));
}
public void subtract()
{
System.out.println("The difference is: "+(a-b));
}
public void product()
{
System.out.println("The product is: "+(a*b));
}
public void division()
{
System.out.println("The quotient is: "+(a/b));
}

package mypackaccess;
import mypack.Calculator;

public class CalculatorDemo {


public static void main(String[] args) {
Calculator c1=new Calculator();
c1.sum();
c1.subtract();
c1.product();
c1.division();
Calculator c2=new Calculator(4,3);
c2.sum();
c2.subtract();
c2.product();
c2.division();

Output:
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).

Program:
package java22scheme;

public class NewRunnableThread implements Runnable {


String name; // name of thread
Thread t;
NewRunnableThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
package java22scheme;

public class NewThread extends Thread {


NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

package java22scheme;

public class ExtendThread {


public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Output:

12.Develop a program to create a class MyThread in this class a conmstructor , 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 thread are
excecuting concurrently.

public class MyThread extends Thread {


public MyThread(String name) {
super(name);
start(); // Start the thread
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output :

You might also like