JAVA MANUAL
JAVA MANUAL
JAVA MANUAL
LAB MANUAL
Syllabus
Part-A-
List of problems for which student should develop program and execute in the
Laboratory
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:
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
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
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.
Algorithm:
1. Begin
2. Display message: "Enter the order N of the matrices."
3. Read N from the user. //Initially keep N<5 for comfort
4. Create two matrices (matrix1 and matrix2) of size N x N.
a. Read elements of the first matrix.
b. Read elements of the second matrix.
5. For all row elements (RowElement 1 to N)
6. For all column elements (Column Element 1 to N)
a. sumMatrix[RowElement, ColumnElement] = Matrix1[RowElement, ColumnElement]+
Matrix2[RowElement, ColumnElement].
7. Display "Sum matrix”
8. End
Program
//This program reads 2 n*n matrices, adds them and displays the sum.
//Author:Anushree
//Package defined
package lab2;
import java.util.Scanner;
my_scanner.close();
}
return sumMatrix;
}
1a) Develop a JAVA program to add TWO matrices of suitable order of N*M.
Algorithm:
1. Initialize the LimitedStack:
Create a LimitedStack object with a maximum size of 10.
2. Display Menu and Get User Choice:
Display a menu with options for push, pop, peek, check if empty, check if full, and exit.
3. Use a loop to repeatedly ask the user for their choice until they choose to exit.
Perform Operations Based on User Choice:
If the user chooses:
• Push (1): Ask the user for a value and push it onto the stack.
• Pop (2): Pop an element from the stack.
• Peek (3): Display the top element of the stack.
• Check if Empty (4): Display whether the stack is empty.
• Check if Full (5): Display whether the stack is full.
• Exit (0): Exit the program.
4. Repeat the process until the user chooses to exit.
5. Close Scanner:
Close the Scanner used for user input.
Program
//Author:Anushree
//Package
package practice;
import java.util.Scanner;
public LimitedStack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Check if empty");
System.out.println("5. Check if full");
System.out.println("0. Exit");
switch (choice) {
case 1:
System.out.print("Enter value to push: ");
int valueToPush = my_scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 5:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting program. Bye!");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
My_scanner.close();
}
}
Extra Challenge
2a) implement a method reverse() that reverses the order of elements in the stack. Demonstrate the usage of this
method in your main program by reversing the elements and displaying the result.
Extra Challenge:
3A)Develop a Java program that defines a class named Employee. The class should include methods to collect details
for two employees, each with an ID, name, and salary. The raiseSalary(percent) method should increase the salary by
the given percentage. Additionally, implement a method to print the details of the employee with the highest salary
increment. Create a suitable main method for demonstration.
Program
package PROJECT;
//Class TestMyPoint
package PROJECT;
4a) Design a Java program that includes a class named MyCircle which represents a circle based on the MyPoint
class. The MyCircle class should have the following features:
Two instance variables: a center (of type MyPoint) representing the center of the circle, and a radius (double)
representing the radius of the circle.
A default constructor that creates a circle with the center at the default location (0, 0) and a default radius.
An overloaded constructor that allows creating a circle with a specific center and radius.
Methods getCenter() and setCenter(MyPoint center) to get and set the center of the circle.
Methods getRadius() and setRadius(double radius) to get and set the radius of the circle.
A method distance(MyCircle another) that returns the distance between the centers of two circles.
Develop the code for the class MyCircle and also create a Java program (called TestMyCircle) to test all the
methods defined in the class.
1.Begin
2.Create a Class Shape with the methods Draw() and erace()
• draw(): Display a message indicating drawing of a generic shape.
• erase(): Display a message indicating erasing a generic shape.
3. Create a Class Circle that extends Shape with Methods:
• draw(): Display a message indicating drawing a circle.
• erase(): Display a message indicating erasing a circle.
4. Create a Class Triangle that extends Shape with Methods:
• draw(): Display a message indicating drawing a triangle.
• erase(): Display a message indicating erasing a triangle.
5. Create a Class Square that extends Shape with the Methods:
• draw(): Display a message indicating drawing a square.
• erase(): Display a message indicating erasing a square.
6. In a Main Program Create objects of Circle, Triangle, and Square. Demonstrate polymorphism by calling draw()
and erase() methods on each object.
7. End.
Program
package project1;
//Subclass Circle
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
}
@Override
public void erase() {
System.out.println("Erasing a circle");
}
}
//Subclass Triangle
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}
@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}
//Subclass Square
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
@Override
public void erase() {
System.out.println("Erasing a square");
}
}
public class Shapes {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
Extra Challenge:
Program 5 a) Include an additional subclass named Area that inherits from the Shape class. Implement a unique
method calculate_area() specific to the Area subclass. In your main program, demonstrate how polymorphism allows
you to treat objects of the Area class interchangeably with objects of the other Shape subclasses.
@Override
public double calculateArea()
{
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter()
{
return 2 * Math.PI * radius;
}
}
Create a Class Triangle
package Abstract;
@Override
public double calculateArea()
{
// Heron's formula to calculate the area of a triangle
@Override
public double calculatePerimeter()
{ return side1 + side2 + side3;
}
}
package Abstract;
6a.Create an abstract class Animal with abstract methods makeSound() and move(). Create two subclasses Dog
and Fish that extend the Animal class and implement the respective methods. In the main method, create instances
of Dog and Fish, call their methods, and display the output.
}
public int getHeight() { return height;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + "]";
}
}
7A) Design a Java program that simulates a basic online shopping system. Create an interface named Purchasable
with methods calculatePrice() and displayDetails(). Develop a class Product that implements the Purchasable
interface. The Product class should have attributes such as name, price, and quantity. Implement the methods to
calculate the total price based on the quantity and display the product details.
Additionally, create a class named ShoppingCart that can hold a collection of Purchasable items. The ShoppingCart
class should have methods to add items, calculate the total cost of all items in the cart, and display the details of
Demonstrate the usage of these classes in a Main class by creating instances of Product, adding them to a
ShoppingCart, and displaying the total cost along with individual product details.
the outer class named inner with a function called display and call the two functions in the main class.
package project1;
package OUTER_CLASS;
class OuterClass {
void display()
{
System.out.println("This is the outer class display method.");
}
// Inner class
class Inner {
void display()
{
System.out.println("This is the inner class display method.");
}
}
}
// Outinclass.java
}
}
Extra Challenge:
Imagine you are designing a Java program to model a multimedia player. Develop a Java program that includes an
outer class named MediaPlayer with a method play. Inside the MediaPlayer class, create an inner class named
AudioPlayer with its own method called playAudio. Both the outer and inner classes should have appropriate
constructors.
playAudio method from the inner class to simulate the playback of audio.
if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
Program-10: Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Create a Java class in the same package that implements the "MyInterface" interface. For example, create a class
named "MyClass" in the "mypack" package:
package mypack;
create a separate Java class in your project (not inside the "mypack" package) to use the "mypack" package:
package Testmypack;
import mypack.*;
public class Test {
public static void main(String[] args)
{
MyInterface myInterfaceObj = new MyClass();
myInterfaceObj.displayMessage("Hello from Main class!");
}
Extra Challenge:
10a) Extend the program to include a new method in the MyPackageClass that calculates the factorial of a number.
Import and use this method in the MainClass to calculate the factorial of a number entered by the user. Implement
proper exception handling to handle non-integer input or negative numbers gracefully. Additionally, provide an
option for the user to calculate the factorial multiple times until they choose to exit the program.
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).
package Thread;
thread1.start();
// Start the first thread
thread2.start(); // Start the second thread
}
}
@Override
public void run() {
try {
System.out.println(threadName + " is running.");
Thread.sleep(500); // Sleep for 500 milliseconds
System.out.println(threadName + " is done.");
}
catch (InterruptedException e)
{ System.err.println(threadName + " was interrupted.");
}
}
}
11a) Extend the program to introduce a third thread (Thread 3) that runs in the background and prints a message
after the other two threads have completed. Implement a mechanism to ensure that the third thread waits for both
Thread 1 and Thread 2 to finish before executing. Use any synchronization technique of your choice.
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
package Thread;
// Main thread
for (int mainThread = 1; mainThread <= 5; mainThread++)
{
System.out.println("Main Thread: " + mainThread);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
System.err.println("Main Thread interrupted");
}
}
@Override
public void run() {
// Child thread
for (int childThread = 1; childThread <= 5; childThread++)
{
System.out.println("Child Thread: " + childThread);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
System.err.println("Child Thread interrupted");
Department of Artificial Intelligence and Data Science, CMRIT, Bangalore.
OOPS with Java Laboratory– BCS306A Academic Year: 2023-24
}
}
Extra Challenge:
12a) Extend the program to introduce a third thread (Child Thread 2) that runs concurrently with both the main
thread and the first child thread. Implement a mechanism to ensure that all three threads (Main Thread, Child Thread
1, and Child Thread 2) print their counts in a synchronized manner, such that the output is sequential and not
interleaved.