JAVA Lab Manual -B Section
JAVA Lab Manual -B Section
BELAGAVI-590018
DEPARTMENT OF CSE
(Artificial Intelligence and Machine Learning)
Dr. Jayasimha S R
USN
NAME
2. Design a class involving data members and methods for the given scenario.
3. Apply the concepts of inheritance and interfaces in solving real world problems.
4. Use the concept of packages and exception handling in solving complex problem
VISION
To emerge as center of academic and research excellence by producing graduates to lead the
Artificial Intelligence-driven technological revolution.
MISSION
Impart quality education in Artificial Intelligence & Machine Learning through state-of-the-art
learning environment.
To build a vibrant community of faculty and students equipped with interdisciplinary Artificial
Intelligence & Machine Learning knowledge and skills to solve real industry specific problems.
To facilitate socially responsive research and innovation center to serve the needs of society.
PRACTICAL COMPONENT OF IPCC
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
read from command line arguments).
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:
● 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 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.
7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width)
and resize Height(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods
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.
Introduction to Object Oriented Programming with JAVA:
Procedural programming is about writing procedures or methods that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
methods.
Pre-requisites:
Let us discuss prerequisites by polishing concepts of method declaration and message
passing. Starting with the method declaration consists of six components:
1. Access Modifier: Defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there are 4 types of access specifiers:
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and expect it to run on any other Java-enabled system without any
adjustment. This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM.
The Class loader reads the “.class” file, generate the corresponding binary data and save it in the
method area. For each “.class” file, JVM stores the following information in the method area.
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum.
Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. These Class
object can be used by the programmer for getting class level information like the name of the class,
parent name, methods and variable information etc. To get this object reference we can
use getClass() method of Object class.
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; //Scanner class is used to get user input, and it is found in the java.util package.
int p, q, m, n;
Scanner s = new Scanner(System.in); //read from the standard input stream of the program
p = s.nextInt();
q = s.nextInt();
m = s.nextInt();
n = s.nextInt();
if (p == m && q == n)
a[i][j] = s.nextInt();
b[i][j] = s.nextInt();
System.out.println("First Matrix:");
System.out.print(a[i][j]+" ");
System.out.println("");
System.out.println("Second Matrix:");
for (int i = 0; i < m; i++)
System.out.print(b[i][j]+" ");
System.out.println("");
System.out.print(c[i][j]+" ");
}
System.out.println("");
else
OUTPUT:
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) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] result = new int[n][n];
System.out.println("Resultant Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
OUTPUT:
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;
while (true) {
System.out.println("\nStack Operations:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
if (top < n - 1) {
System.out.println("Enter value to push: ");
int value = scanner.nextInt();
stack[++top] = value;
} else {
System.out.println("Stack is full. Can't push value.");
}
break;
case 2:
if (top >= 0) {
System.out.println("Popped value: " + stack[top--]);
} else {
System.out.println("Stack is empty. Can't pop value.");
}
break;
case 3:
if (top >= 0) {
System.out.println("Stack content: ");
for (int i = top; i >= 0; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
OUTPUT:
Enter the number of values (n):
10
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
1
Enter value to push:
10
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
1
Enter value to push:
20
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
Stack content:
20 10
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
2
Popped value: 20
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
Stack content:
10
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
4
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;
OUTPUT:
Enter Employee ID:
722
Enter Employee Name:
arun
Enter Employee Salary:
200000
Employee Details Before Raise:
Employee ID: 722
Name: arun
Salary: 200000.0
Enter percentage to raise salary:
50
Employee Details After Raise:
Employee ID: 722
Name: arun
Salary: 300000.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.
Note:this program contains 2 main JAVA (.java) classes in the terminal compile MyPoint.java first and
compile TestMyPoint.java then run TestMyPoint.java to get the OUTPUT
This TestMyPoint program creates two MyPoint objects, sets and retrieves coordinates, and tests the various
distance calculation methods.
Java Code
MyPoint.java
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
// Set both x and y
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
TestMyPoint.java
OUTPUT:
import java.util.Scanner;
// Shape class (Parent)
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
void erase() {
System.out.println("Erasing a shape");
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}
@Override
void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}
@Override
void erase() {
System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}
Square(double side) {
this.side = side;
}
@Override
void draw() {
System.out.println("Drawing a square with side " + side);
}
@Override
void erase() {
System.out.println("Erasing a square with side " + side);
}
}
switch (choice) {
case 1:
System.out.print("Enter circle radius: ");
double radius = scanner.nextDouble();
shape = new Circle(radius);
break;
case 2:
System.out.print("Enter triangle base: ");
double base = scanner.nextDouble();
System.out.print("Enter triangle height: ");
double height = scanner.nextDouble();
shape = new Triangle(base, height);
break;
case 3:
System.out.print("Enter square side: ");
double side = scanner.nextDouble();
shape = new Square(side);
break;
default:
System.out.println("Invalid choice");
}
if (shape != null) {
shape.draw();
shape.erase();
}
}
}
OUTPUT:
import java.util.Scanner;
// Circle subclass
class Circle extends Shape {
private double radius;
@Override
double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
// Triangle subclass
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;
@Override
double calculateArea() {
// Calculate semi-perimeter
double s = (side1 + side2 + side3) / 2;
// Use Heron's formula
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
System.out.println("Choose a shape:");
System.out.println("1. Circle");
System.out.println("2. Triangle");
switch (choice) {
case 1:
System.out.print("Enter circle radius: ");
double radius = scanner.nextDouble();
shape = new Circle(radius);
break;
case 2:
System.out.print("Enter side 1: ");
double side1 = scanner.nextDouble();
System.out.print("Enter side 2: ");
double side2 = scanner.nextDouble();
System.out.print("Enter side 3: ");
double side3 = scanner.nextDouble();
shape = new Triangle(side1, side2, side3);
break;
default:
System.out.println("Invalid choice");
System.exit(1);
}
OUTPUT:
Choose a shape:
1. Circle
2. Triangle
1
Enter circle radius: 2.0
Area: 12.566370614359172
Perimeter: 12.566370614359172
Choose a shape:
1. Circle
2. Triangle
2
Enter side 1: 2.0
Enter side 2: 3.0
Enter side 3: 3.0
Area: 2.8284271247461903
Perimeter: 8.0
Choose a shape:
1. Circle
2. Triangle
1
Enter circle radius: 2.0
Area: 12.566370614359172
Perimeter: 12.566370614359172
________________________________________________________________________________
Program 7:
// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
@Override
public void resizeWidth(int width) {
this.width = width;
}
@Override
public void resizeHeight(int height) {
this.height = height;
}
while (choice.equals("yes")) {
System.out.println("Choose resize option:");
System.out.println("1. Resize width");
System.out.println("2. Resize height");
System.out.println("3. Resize both");
OUTPUT:
// Constructor
public Outer(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
// Inner class
public class Inner {
// Inner class display method
public void display() {
int result = num1 + num2;
System.out.println("Inner class display method:");
System.out.println("Result: " + result);
}
}
}
// Main class
public class Main {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
OUTPUT:
try {
if (divisor == 0) {
throw new DivisionByZero("Cannot divide by zero!");
}
int quotient = divide(dividend, divisor);
System.out.println("Quotient: " + quotient);
} catch (DivisionByZero e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
Output:
mypack/MyClass.java:
package mypack;
mypack/MyInterface.java:
java
package mypack;
`mypack/MySubClass.java`:
package mypack;
`MainClass.java`:
import mypack.*;
Instead of importing all classes using `import mypack.*;`, you can import specific classes:
import mypack.MyClass;
import mypack.MySubClass;
java MainClass
Output:
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " is running. Iteration: " + i);
try {
Thread.sleep(500); // Suspend thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(threadName + " is interrupted.");
}
}
}
}
// Create threads
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
Thread thread3 = new Thread(runnable3);
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
``
Output:
Output: