AIML - Java - Manual-2024-25
AIML - Java - Manual-2024-25
LABORATORY MANUAL
Prepared by
Prof. MUNIRAJU M
Assistant Professor
Department of Artificial Intelligence & Machine Learning
SJC Institute of Technology
2024-25
Sl no. Program
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
1
read from command line arguments).
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
2
JAVA main method to illustrate Stack operations.
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
3
by the given percentage. Develop the Employee class and suitable main method for
demonstration.
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
4
● 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 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.Develop the code for
the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all the methods
defined in the 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 ().
5
Demonstrate polymorphism concepts by developing suitable methods, defining member data
and main program.
Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend the
6
Shape class and implement the respective methods to calculate the area and perimeter of each
shape.
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width)
7 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
Develop a JAVA program to create an outer class with a function display. Create another class
8 inside the outer class named inner with a function called display and call the two functions in
the main class.
Develop a JAVA program to raise a custom exception (user defined exception) for
9
DivisionByZero using try, catch, throw and finally.
Develop a JAVA program to create a package named mypack and import & implement it in a
10
suitable class.
Write a program to illustrate creation of threads using runnable class. (start method start each
11 of the newly created thread. Inside the run method there is sleep() for suspend the thread for
500 milliseconds).
Develop a program to create a class MyThread in this class a constructor, call the base class
12 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.
Object Oriented Programming with JAVA
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).
class matrixAddition
{
public static void main(String []args)
{
if (args.length != 1) {
System.out.println("Please provide the value of N as a command-line argument.");
return;
}
System.out.println(args[0]);
int N = Integer.parseInt(args[0]);
System.out.println("Matrix B:");
displayMatrix(matrixB);
}
}
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.
package stack;
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;
}
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display Stack Contents");
System.out.println("5. Check if the stack is empty");
System.out.println("6. Check if the stack is full");
System.out.println("0. Exit");
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 6:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();
Output
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.
Output
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;
}
Output
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.
class Shape {
protected String name;
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}
@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}
@Override
@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}
@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}
Output
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.
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
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
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
Output:
Program 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.
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
rectangle.resizeWidth(15);
rectangle.resizeHeight(8);
Out put
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");
}
}
}
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
}
Output
Program 9.Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
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
Program 10. Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
package mypack;
import mypack.MyPackageClass;
//import mypack.*;
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).
@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.");
}
}
}
Output
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.
// 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
4. What is an object?
An object is a real-world entity which is the basic unit of OOPs for example chair, cat, dog, etc. Different
objects have different states or attributes, and behaviors.
5. What is a class?
A class is a prototype that consists of objects in different states and with different behaviors. It has a
number of methods that are common the objects present within that class.
6. What is the difference between a class and a structure?
Class: User-defined blueprint from which objects are created. It consists of methods or set of instructions
that are to be performed on the objects.
Structure: A structure is basically a user-defined collection of variables which are of different data types.
7. Can you call the base class method without creating an instance?
Yes, you can call the base class without instantiating it if:
It is a static method
The base class is inherited by some other subclass
Object Class
A class is basically a template or a blueprint within
A real-world entity which is an instance of a class
which objects can be created
An object acts like a variable of the class Binds methods and data together into a single unit
An object is a physical entity A class is a logical entity
Objects take memory space when they are created A class does not take memory space when created
Objects can be declared as and when required Classes are declared just once
9. What is inheritance?
Inheritance is a feature of OOPs which allows classes inherit common properties from other classes. For
example, if there is a class such as ‘vehicle’, other classes like ‘car’, ‘bike’, etc can inherit common
properties from the vehicle class. This property helps you get rid of redundant code thereby reducing the
overall size of the code.
10. What are the different types of inheritance?
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
means that they do not contain any definition in the base class and need to be redefined in the subclass.