java lab program with output
java lab program with output
Experiment 1:
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)
{
int m, n;
int a[][], b[][], c[][];
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the size of matrix(row, col) : ");
m = scanner.nextInt();
n = scanner.nextInt();
System.out.println("Enter the elements of first matrix");
a = readMatrix(m,n);
System.out.println("Enter the elements of second matrix");
b = readMatrix(m,n);
c = addMatrix(a,b);
System.out.println("Result");
printMatrix(c);
}
a[i][j] = scanner.nextInt();
return a;
}
System.out.println();
}
}
Output:
Result
64
69
Experiment 2:
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.
Aim: The aim of this program is to implement a basic stack data structure in Java that can hold
a maximum of 10 integers.
Learning Objectives: To learn primitive constructs Java programming language
Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:
Stack: A stack stores data using first-in, last-out ordering. That is, a stack is like a stack of plates
on a table—the first plate put down on the table is the last plate to be used. Stacks are controlled
through two operations traditionally called push and pop. To put an item on top of the stack, you
will use push. To take an item off the stack, you will use pop.
Stack operations: The method push( ) puts an item on the stack. To retrieve an item, call pop( ).
Since access to the stack is through push( ) and pop( ), the fact that the stack is held in an array is
actually not relevant to using the stack. For example, the stack could be held in a more
complicated data structure, such as a linked list, yet the interface defined by push( ) and pop( )
would remain the same.
//Stack.java
public class Stack
{
final int MAX = 10;
int s[] = new int[MAX];
int top = -1;
import java.util.Scanner;
//StackDemo.java
public class StackDemo
{
public static void main(String args[])
{
Stack stack = new Stack();
System.out.println("Program to perform stack operations");
{
System.out.println("1. push 2.pop 3. display 4.Exit");
System.out.println("Enter your choice");
int choice = scanner.nextInt();
int element = 0;
switch (choice)
{
case 1:
System.out.println("enter the element to be pushed");
element = scanner.nextInt();
stack.push(element);
break;
case 2:
element = stack.pop();
System.out.println("the poped element is" + element);
break;
case 3:
System.out.println("elements in the stack are");
stack.display();
break;
case 4:
return;
}
}
}
}
Output:
Experiment 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.
Aim: This program is to model an Employee class that represents employees with an ID, name,
and salary.
Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:
class is a template for an object, and an object is an instance of a class.
Methods:
Methods define the behavior of an object. They represent actions that objects of a class can perform. In
Java, you define methods within a class.
//Employee.java
public class Employee {
private int id;
private String name;
private int salary;
}
}
//EmployeeDemo.java
import java.util.Scanner;
Output:
Experiment 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
Aim: The aim of the provided program is to create a class called MyPoint that models a 2D
point with x and y coordinates, and then develop a Java program (TestMyPoint) to test all the
methods defined in the MyPoint class.
Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:
The MyPoint class is designed to represent and manipulate points in a 2D plane. The class
includes various constructors and methods for setting coordinates, getting coordinates,
calculating distances, and generating a string representation of a MyPoint instance.
Constructor:
A constructor initializes an object immediately upon creation. It has the same name as
the class in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called when the object is created, before the new
operator completes.
Overloading Methods:
In Java, it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism. If you have never used
a language that allows the overloading of methods, then the concept may seem strange at first.
But as you will see, method overloading is one of Java’s most exciting and useful features.
Default Constructor:
In Java, a default constructor explicitly defined in a class. The default constructor has no
parameters and initializes the object with default is a special type of constructor that is
automatically provided by the compiler if no other constructor is values.
Key points about default constructors:
public MyPoint()
{
this.x = 0;
this.y = 0;
}
{
double dist = 0.0;
return dist;
}
import java.util.Scanner;
while (true)
{
System.out.println("1. Distance to origin");
System.out.println("2. Distance from point (x,y)");
System.out.println("3. Distance from Point object");
System.out.println("0. Exit");
System.out.println("Enter your choice : ");
choice = scanner.nextInt();
switch ( choice )
{
case 1 :
distance = point.distance();
break;
case 2 :
System.out.println("Enter coordinates of other point");
x = scanner.nextInt();
y = scanner.nextInt();
distance = point.distance(x,y);
break;
case 3:
System.out.println("Enter coordinates of other point");
x = scanner.nextInt();
y = scanner.nextInt();
MyPoint point1 = new MyPoint(x,y);
distance = point.distance(point1);
break;
case 0:
return;
}
System.out.println("Distance : " + distance);
}
}
}
Output:
Enter the co-ords of Point under consideration
1
2
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice :
1
distance: 2.23606797749979
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice:
2
Enter coordinates of other point
6
8
distance: 7.810249675906654
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice:
3
Enter coordinates of other point
5
6
Distance: 5.656854249492381
Experiment 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.
Aim: The aim of this Java program is to demonstrate polymorphism by creating a class
hierarchy for geometric shapes. The base class Shape contains two methods, draw() and erase(),
and three subclasses (Circle, Triangle, and Square) inherit from it. Each subclass overrides the
draw() and erase() methods to provide their own implementation.
Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:
1. Polymorphism:
Member functions are methods defined within a class. They represent the behavior or
actions that objects of the class can perform.
Data members are variables declared within a class. They represent the state or attributes of
objects of the class.
Output:
circle.draw( )…
circle.erase( )…
triangle.draw( )…
triangle.erase( )…
square.draw( )…
square.erase( )…
Experiment 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.
Aim: The program is to demonstrate the concept of abstract classes and abstract methods. The
program defines an abstract class Shape with two abstract methods: calculateArea() and
calculatePerimeter().
Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems.
Theory:
Subclass:
A subclass, also known as a derived class or child class, is a class that inherits properties and
behaviors from another class called the super-class or parent class. The subclass can extend the
functionality of the super-class by adding new methods or overriding existing methods.
Abstract Method:
Abstract Class:
An abstract class is a class that cannot be instantiated on its own. It may contain abstract methods
(methods without a body) that must be implemented by concrete subclasses. Abstract classes can
also have concrete methods with an implementation. Abstract classes provide a way to define a
common interface for a group of related classes.
@Override
public float calculatePerimeter() {
return (float) (2 * Math.PI * radius);
}
@Override
public float calculateArea() {
return (float) (Math.PI * radius * radius );
}
}
public abstract class Shape {
public abstract float calculatePerimeter();
public abstract float calculateArea();
import java.util.Scanner;
float perimeter;
float area;
Shape shape;
switch ( option )
{
case 1 :
System.out.println("Enter radius : ");
radius = scanner.nextInt();
shape = new Circle(radius);
perimeter = shape.calculatePerimeter();
area = shape.calculateArea();
System.out.println("Perimeter : " + perimeter);
System.out.println("Area : " + area);
break;
case 2 :
System.out.println("Enter 3 sides of triangle : ");
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
shape = new Triangle(a,b,c);
perimeter = shape.calculatePerimeter();
area = shape.calculateArea();
System.out.println("Perimeter : " + perimeter);
System.out.println("Area : " + area);
break;
}
}
}
public class Triangle extends Shape {
private int a;
private int b;
private int c;
@Override
public float calculatePerimeter() {
return (float) (a + b + c);
}
@Override
public float calculateArea() {
float s = (float)((a+b+c) / 2.0);
float area = (float)Math.sqrt(s * (s-a) * (s-b) * (s-c));
return area;
}
}
Output:
1. Circle
2. Triangle
Enter your option
1
Enter radius:
15
Perimeter: 94.24778
Area: 706.85834
Enter your option
2
Enter 3 sides of triangle
2
3
4
Perimeter:
Area:
Experiment 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
Aim: The program is to demonstrate the use of interfaces and implementation of the Resizable
interface in a class. In this case, an interface named Resizable is defined with methods
resizeWidth(int width) and resizeHeight(int height) to allow an object to be resized. The program
then creates a class Rectangle that implements the Resizable interface and provides concrete
implementations for the resize methods.
Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems
Theory:
Interface in Java:
An interface in Java is a collection of abstract methods. It represents a contract that a class must
adhere to by providing concrete implementations for all the methods declared in the interface.
Interfaces can also include constants (variables with the final modifier) and default methods
(methods with a default implementation).Resizable Interface:
In the provided program, the Resizable interface is defined with two abstract methods:
resizeWidth(int width) and resizeHeight(int height). These methods declare a contract that any
class implementing the Resizable interface must provide concrete implementations for resizing
an object's width and height.
Rectangle Class:
The Rectangle class implements the Resizable interface. It has two private fields, width and
height, to represent the dimensions of the rectangle. The class provides a constructor to initialize
these dimensions, as well as getter methods to retrieve them.
public Rectangle()
{
@Override
public void resizeHeight(int height) {
this.height = height;
}
@Override
public void resizeWidth(int width) {
this.width = width;
}
import java.util.Scanner;
int height = 0;
int width = 0;
System.out.println(resizable);
}
}
Output:
Experiment: 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.
Aim: The program is to demonstrate the concept of inner classes. The program defines an outer
class (OuterClass) with a function display. Inside the outer class, there is an inner class (Inner)
that also has a function display. The main class (MainClass) creates an instance of both the outer
and inner classes and calls their respective display methods to showcase how outer and inner
classes can coexist and have separate implementations of the same method.
Learning Objectives: To understand Object Oriented Programming Features of JAVA
Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems.
Theory:
Inner Classes in Java:
An inner class is a class defined within another class. In Java, inner classes provide a way to
logically group classes that are only used in one place, and they increase encapsulation.
Anonymous Inner Class: Without a name, defined for implementing interfaces or extending
classes on the spot.
A member inner class is defined inside another class as a member of that class. It has access to
the members (fields and methods) of its outer class, including private members.
MainClass:
In the MainClass, an instance of the outer class (OuterClass) is created, and its display method is
called.
An instance of the inner class (Inner) is created using the outer class instance, and its display
method is called.
class Inner
{
public void display()
{
System.out.println("Inside Inner.display()");
}
}
}
Outer.Inneri = o.newInner();
i.display();
}
}
Output:
Inside Outer.display( )
Inside Inner.display( )
Experiment: 9
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionBy
Zero using try, catch, throw and finally.
Aim: The program is to demonstrate the use of custom exceptions. The program defines a
custom exception class (DivisionByZeroException) that extends the built-in Exception class. The
program performs a division operation and throws the custom exception if a division by zero is
detected.
Theory:
Custom Exception (User-Defined Exception):
In Java, we create our own exceptions by extending the Exception class or one of its subclasses.
These are known as custom exceptions or user-defined exceptions. Creating custom exceptions
allows you to handle specific error conditions in a more structured and meaningful way.
Explanation:
The DivisionByZeroException class extends the built-in Exception class and has a constructor
that takes a message.
The divide method in the main program performs division and throws a Division By Zero
Exception if the denominator is zero.
In the main method, a try block is used to enclose the code that might throw an exception.
The catch block catches and handles the custom exception if it occurs.
The finally block contains code that always executes, whether an exception is thrown or not.
This block is useful for cleanup or releasing resources.
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args)
{
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the divisor : ");
n = scanner.nextInt();
try
{
int quotient = 22 / n;
System.out.println("quotient : " + quotient);
}
catch(ArithmeticException ae)
{
try
{
throw new MyException();
}
catch(MyException me)
{
}
}
}
}
Output:
44
quotient : 0
MyException.constructor( )…
Experiment 10:
Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Aim:
This program aims to illustrate the process of creating and utilizing packages in Java for better
code organization, modularity, and reusability.
Learning Objectives: To gain knowledge on: packages, multithreaded programming and
exceptions.
Course outcome:
CO4: Use the concept of packages and exception handling in solving complex problem
Theory:
Packages in Java:
In Java, a package is a way to organize related classes and interfaces into a single directory
hierarchy. It helps in preventing naming conflicts, improves code modularity, and enhances code
reusability. A package can contain subpackages, and classes in a package can be grouped
logically.
Package (mypack):
The MyPackageClass class has a method displayMessage() that prints a simple message.
It imports the MyPackageClass from the mypack package using the import statement.
In the main method, an instance of MyPackageClass is created, and its displayMessage method is
called.
package pgm10.mypack;
public class MyClass {
public void display()
{
System.out.println("Inside MyClass.display() method ...");
}
}
import pgm10.mypack.MyClass;
Output:
Experiment 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).
Aim: The program is to demonstrate the creation of threads using the Runnable interface. The
program aims to illustrate the basics of multi-threading, thread creation, and the concept of
thread suspension.
Learning Objectives: Gain hands-on experience with multi-threading concepts, including
creating and managing multiple threads in a Java program
Course outcome:
CO5: Apply concepts of multithreading, autoboxing and enumerations in program development
Theory:
The Thread class in Java provides a constructor that takes a Runnable object as an argument.
When a Thread object is created with a Runnable object, it can start a new thread of execution,
and the run() method of the Runnable object will be executed in that thread.
We can create threads using the Runnable interface. The Runnable interface represents a task
that can be executed concurrently by a thread. To use the Runnable interface, you typically
create a class that implements Runnable and override its run() method. The run() method
contains the code that will be executed when the thread is started.
Explanation:
MyRunnable is a class that implements the Runnable interface. It overrides the run() method,
where the thread sleeps for 500 milliseconds.
Two Thread objects (thread1 and thread2) are created, each associated with one of the
MyRunnable instances.
The start() method is called on each Thread object to begin the execution of the associated run()
method.
While the new threads are running, the main thread also continues its execution, printing
messages to the console.
The start() method of the Thread class is used to initiate the execution of the thread. It internally
calls the run() method of the Runnable object.
The sleep() method is used to make the thread sleep for a specified amount of time. In this
example, it's used to simulate some work being done by the threads
t1.setName("JIT1");
t2.setName("JIT2");
t3.setName("JIT3");
t1.start();
t2.start();
t3.start();
Output:
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
Experiment 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.
Aim: The program aims to illustrate the concurrent execution of the main thread and the child
thread, highlighting the concepts of thread creation, base class constructors, and concurrent
execution.
Learning Objectives: To gain knowledge on: packages, multithreaded programming and
exceptions.
Course outcome:
CO5: Apply concepts of multithreading, auto-boxing and enumerations in program
development
Theory:
In Java, multithreading allows multiple threads to run concurrently, providing a way to execute
multiple tasks simultaneously. To create a thread, you can extend the Thread class or implement
the Runnable interface. In this case, let's extend the Thread class.
When extending the Thread class, you override the run() method with the code that will be
executed when the thread is started. You can also provide a constructor to initialize any specific
attributes of your thread.
When a new thread is created by extending the Thread class, the start() method must be called to
begin the execution of the thread. The start() method internally calls the run() method.
The main thread and the created child thread run concurrently, executing their respective code in
parallel.
The Thread.sleep() method is used to introduce a short delay, simulating some work being done
by the threads.
@Override
public void run()
{
for ( inti = 0; i< 50; i++ )
System.out.println("run() : " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
Output:
main
main
main
main
main
main
main
main
main
main
main
main
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT