Java Lab Manual III Sem 23
Java Lab Manual III Sem 23
MRIT
Student Name :. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Branch : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Semester : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Hands on Experiments
1
2
3
4
5
6
7
8
9
10
11
12
Total Average Marks Obtained
Total Marks Scale down to 25 Marks Obtained after Scale down [A]
Total Marks Scale down to 25 Marks Obtained after Scale down [B]
Final practical CIE marks obtained from Conduction of Experiments and Practical Test = [A]+[B]
Final CIE for 50 Marks = [A]+[B] [A] = [B] = Total Marks
Note: Minimum passing marks is 20 Marks from [A] & [B];with [A] = 10 marks and [B] = 10 marks
Output:
Sum of matrices is:
0 2 4
2 4 6
6 8 7
public void
push (int value)
{
if (top == maxSize - 1)
{
System.out.println("Stack is full. Unable to
push " + value);
return;
}
stackArray[++top] = value;
}
public void
pop ()
{
if (top == -1)
{
System.out.println ("Stack is empty");
return;
}
System.out.println ("Popped " + stackArray[top--] + "from the
stack");
}
public void
display ()
{
if (top == -1)
{
System.out.println ("Stack is empty");
return;
}
System.out.print ("Stack: ");
for (int i = 0; i <= top; i++)
{
case 2:
stack.pop ();
break;
case 3:
stack.display ();
break;
case 4:
scanner.close ();
return;
default:
System.out.println("Invalid option.Please
choose again.");
}
}
}
}
Output:
Choose an option:
1) Push
2) Pop
3) Display
4) Exit
Stack: 10 20 30
Choose an option:
1) Push
2) Pop
3) Display
4) Exit
Stack: 10 20
Output:
Enter Employee ID:
1
Enter Employee Name:
ABC
Enter Employee Salary:
20000
Employee ID: 1
Employee Name: ABC
Employee Salary: 20000.0
Enter raise percentage:
15
Employee Salary after raise: 23000.0
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(0, 0); }
// Overloaded Constructor
public MyPoint (int x, int y)
{
this.x = x;
this.y = y;
}
// Setters
public void
setXY (int x, int y)
{
this.x = x;
this.y = y;
}
// Getters
public int[] getXY ()
{
int[] coordinates = { x, y };
Output:
Point 1: (5, 6)
Point 2: (3, 4)
Point 2 coordinates: (3, 4)
Distance from Point 1 to (5, 6): 0.0
Distance from Point 2 to Point 1: 2.8284271247461903
Distance from Point 2 to origin: 5.0
public void
erase ()
{
System.out.println ("Erasing a shape");
}
}
class Circle extends Shape
{
@Override
public void
draw ()
{
System.out.println ("Drawing a circle");
}
@Override
public void
erase ()
{
System.out.println ("Erasing a circle");
}
}
class Triangle extends Shape
{
@Override
public void
draw ()
{
System.out.println ("Drawing a triangle");
}
@Override
public void
erase ()
{
@Override
public void
erase ()
{
System.out.println ("Erasing a square");
}
}
public class ShapeMain
{
public static void main (String[] args)
{
Shape[] shapes = new Shape[3];
shapes[0] = new Circle ();
shapes[1] = new Triangle ();
shapes[2] = new Square ();
for (Shape shape : shapes)
{
shape.draw ();
shape.erase ();
System.out.println (); // Add a line break for clarity
}
}
}
Output:
Drawing a circle
Erasing a circle
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square
// Constructor
public Circle (double radius) { this.radius = radius; }
@Override
public double
calculateArea ()
{
return Math.PI * radius * radius;
}
@Override
public double
calculatePerimeter ()
{
return 2 * Math.PI * radius;
}
}
class Triangle extends Shape
{
private double side1;
private double side2;
private double side3;
// Constructor
public Triangle (double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
public double
@Override
public double
calculatePerimeter ()
{
return side1 + side2 + side3;
}
}
public class Shape_peri_area_Main
{
public static void main (String[] args)
{
Circle circle = new Circle (5.0);
Triangle triangle = new Triangle (3.0, 4.0, 5.0);
System.out.println ("Circle:");
System.out.println ("Area: " + circle.calculateArea ());
System.out.println ("Perimeter: " + circle.calculatePerimeter
());
System.out.println ();
System.out.println ("Triangle:");
System.out.println ("Area: " + triangle.calculateArea ());
System.out.println ("Perimeter: " +
triangle.calculatePerimeter ());
}
}
Output:
Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793
Triangle:
Area: 6.0
Perimeter: 12.0
// Constructor
public Rectangle (int width, int height)
{
this.width = width;
this.height = height;
}
@Override
public void
resizeWidth (int width)
{
this.width = width;
}
@Override
public void
resizeHeight (int height)
{
this.height = height;
}
rectangle.resizeWidth (8);
rectangle.resizeHeight (10);
Output:
Original Dimensions:
Width: 5, Height: 7
Resized Dimensions:
Width: 8, Height: 10
class Inner
{
void display()
{
System.out.println("Inner display");
}
}
}
Output:
Outer display
Inner display
Output:
Exception: Cannot divide by zero
Finally block executed
Step 2: Define the Class in the Package. Open MyClass.java and add the following code:
package mypack;
public class MyClass
{
public void
display ()
{
System.out.println("This is a method from the mypack
package.");
}
}
import mypack.MyClass;
Output:
This is a method from the mypack package.
Output:
Thread 10 is running.
Thread 12 is running.
Thread 14 is running.
Thread 13 is running.
Thread 11 is running.
public void
run ()
{
try
{
for (int i = 5; i > 0; i--)
{
System.out.println (getName () + ": " + i);
Thread.sleep (1000);
}
}
catch (InterruptedException e)
{
System.out.println (getName () + " interrupted.");
}
System.out.println (getName () + " exiting.");
}
}
try
{
for (int i = 5; i > 0; i--)
{
System.out.println ("Main Thread: " + i);
Thread.sleep (2000);
}
}
catch (InterruptedException e)
Output:
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Child Thread exiting.
Main Thread: 2
Main Thread: 1
Main Thread exiting.
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
A3: Encapsulation is the process of hiding the internal state and behavior of an object and
exposing only the necessary information or methods. It is achieved through access modifiers like
public, private, and protected.
A4: Inheritance is a mechanism in OOP that allows one class (subclass) to inherit the attributes
and methods of another class (superclass). This promotes code reuse and allows for the creation
of more specialized classes.
A5: Polymorphism allows objects to take on multiple forms. In Java, it can be achieved through
method overloading and method overriding. Method overloading involves having multiple
methods with the same name but different parameter lists, while method overriding involves
redefining a method in a subclass with the same signature as the superclass.
A6: Abstraction involves creating a simplified representation of an object with only the relevant
details, while hiding the unnecessary complexities. In Java, this is achieved through abstract
classes and interfaces.
2. Java Basics:
Q7: What is Java Virtual Machine (JVM)?
A7: JVM is an abstract machine that provides the runtime environment for executing Java
applications. It interprets the compiled Java bytecode and translates it into machine-specific
instructions.
A8: JDK (Java Development Kit) is a software development kit that includes tools for
developing, debugging, and monitoring Java applications. JRE (Java Runtime Environment) is
an environment that provides the necessary runtime components to execute Java applications.
A9: A class in Java is a blueprint for creating objects. It defines the structure (attributes) and
behavior (methods) that the objects of the class will have.
A10: An object is an instance of a class. It is a real-world entity with a unique identity, state
(attributes), and behavior (methods).
A11: You can declare a variable in Java using the syntax: datatype variableName; For
example: int age;
A12: The if-else statement allows you to execute different blocks of code based on a condition.
If the condition is true, the code inside the if block is executed; otherwise, the code inside the
else block is executed.
A13: The switch statement allows you to select one of many code blocks to be executed. It
evaluates an expression and matches it with various case labels to determine which block of code
to execute.
A14: A for loop is a control flow statement that allows you to execute a block of code repeatedly
for a fixed number of times. It typically consists of an initialization, a condition, and an
increment or decrement operation.
Q15: How does a while loop work in Java?
A15: A while loop repeatedly executes a block of code as long as a specified condition is true. It
evaluates the condition before each iteration.
A16: A do-while loop is similar to a while loop, but it ensures that the block of code is executed
at least once, regardless of whether the condition is true or false.
A17: You can declare an array in Java using the syntax: datatype[] arrayName; For example:
int[] numbers;
A18: An array is a fixed-size data structure that can hold elements of the same type. An
ArrayList is a dynamic-sized collection class provided by the Java Collections Framework that
can dynamically grow and shrink as needed.
A19: The List interface in Java is an ordered collection of elements that allows duplicates. It
defines methods for adding, removing, and accessing elements by index.
A20: A Set is a collection that does not allow duplicate elements, whereas a List allows
duplicates. Additionally, elements in a Set are not ordered, while elements in a List are ordered
and have an index.
5. Exception Handling:
A21: An exception in Java is an event that occurs during the execution of a program and disrupts
the normal flow of instructions. It can be caused by various factors, such as invalid input or
runtime errors.
A23: The finally block is used to specify code that will be executed regardless of whether an
exception occurs or not. It is typically used for cleanup operations.
A24: Checked exceptions are checked at compile time and must be either caught or declared in
the method signature using the throws keyword. Unchecked exceptions (also known as runtime
exceptions) do not need to be explicitly handled.
A25: A thread is the smallest unit of execution within a process. It allows a program to perform
tasks concurrently and asynchronously.
A28: wait() is a method in the Object class that causes the current thread to wait until another
thread invokes the notify() or `notify
A28: wait() is a method in the Object class that causes the current thread to wait until another
thread invokes the notify() or notifyAll() method for this object. It's typically used for inter-
thread communication.
On the other hand, sleep() is a method in the Thread class that temporarily suspends the
execution of a thread for a specified amount of time, allowing other threads to execute. It does
not release any locks the thread may hold.
7. File Handling:
A29: To read from a file in Java, you can use classes like FileInputStream, BufferedReader,
or Scanner. You'll typically open the file, read its contents, and then close the file.
A30: File is a class in Java that represents a file or directory's pathname. It provides methods for
obtaining information about the file/directory, creating new files or directories, etc.
FileInputStream, on the other hand, is a class that is used to read bytes from a file. It's
typically used in combination with other classes like InputStreamReader to read characters.
A31: A package in Java is a way to organize related classes and interfaces into a single unit. It
helps in avoiding naming conflicts and provides a clear structure for large projects.
A32: You can import classes from a package using the import statement. For example, import
packageName.className; allows you to use className from the packageName package.
A33: The default package in Java is the package that contains all classes that have no package
declaration. It's recommended to avoid using the default package for larger projects.
A34: An interface in Java is a blueprint of a class that defines a set of methods without
implementation. It serves as a contract, ensuring that classes that implement the interface provide
the specified behavior.
A36: An abstract class in Java is a class that cannot be instantiated directly. It serves as a
blueprint for other classes to extend and provides a common interface for a group of related
classes.
A37: Yes, an abstract class can have both abstract and non-abstract (concrete) methods. It may
also have attributes and constructors.
A38: Method overriding occurs when a subclass provides a specific implementation for a method
that is already defined in its superclass. The method in the subclass has the same signature
(name, return type, and parameters) as the method in the superclass.
A39: super is a keyword in Java used to refer to the superclass, while this is used to refer to the
current instance of a class. super is often used to call overridden methods or access superclass
members.
A40: Dynamic polymorphism is achieved through method overriding. When a method is called
on an object, the JVM determines at runtime which version of the method to execute based on
the actual type of the object.
A42: A Stream in Java 8+ is a sequence of elements that supports various operations (like
filtering, mapping, reducing) to be performed on the elements in a functional style.
Q43: How is a Stream different from a Collection in Java?
A43: A Collection is an in-memory data structure that holds a fixed set of elements, whereas a
Stream is a sequence of elements that can be processed in a functional-style manner. Streams do
not store elements; they carry values from a source, through a pipeline of operations.
A44: An annotation in Java is a form of syntactic metadata that provides additional information
about code. They are used for various purposes, such as providing information to the compiler,
runtime, or other tools.
A45: Reflection in Java is a mechanism that allows a program to examine or modify its own
structure, behavior, and state at runtime. It provides a way to inspect and invoke methods, access
fields, and create new classes.
A46: Sure! One common annotation in Java is @Override, which is used to indicate that a
method in a subclass is intended to override a method in its superclass.
java
class Parent {
public void display() {
System.out.println("Parent class");
}
}
A47: Object serialization in Java is the process of converting an object into a byte stream, which
can be stored or transmitted, and later reconstructed back into an object.
import java.io.Serializable;
A49: serialVersionUID is a unique identifier for a serialized object. It's used during
deserialization to ensure that the class that was used for serialization is compatible with the class
used for deserialization.
A50: The Singleton design pattern ensures that a class has only one instance and provides a
global point of access to that instance. It is often used for resources that need to be shared across
the application
Questions based on the lab programs:
1. Matrix Addition
Q1: Explain how you would read the order of matrices from command line arguments in Java.
A1: To read the order of matrices from command line arguments, you can use the args parameter
in the main method. For example, if you run the program with java MatrixAddition 3, you can access
the value 3 using args[0].
Q2: How would you implement the addition of two matrices in Java?
A2: To add two matrices in Java, you would first create two 2D arrays representing the matrices.
Then, you would iterate through the elements of both arrays, adding corresponding elements and
storing the result in a new matrix.
2. Stack Operations
Q4: How would you implement a stack in Java? Explain the methods involved.
A4: To implement a stack in Java, you can use an array or linked list. You would create a class
with methods like push, pop, peek, and isEmpty. The push method adds an element to the stack, pop
removes and returns the top element, peek returns the top element without removing it, and
isEmpty checks if the stack is empty.
3. Employee Class
Q5: Explain the purpose of the Employee class and its attributes.
A5: The Employee class models an employee with attributes like ID, name, and salary. It is used
to store information about an employee in a program.
A6: The raiseSalary(percent) method would take a percentage as an argument and increase the
employee's salary accordingly. Inside the method, you would calculate the new salary based on
the given percentage and update the employee's salary attribute.
4. MyPoint Class
A7: The MyPoint class has two integer attributes, x and y, representing the coordinates of a 2D
point.
Q8: Explain how you would calculate the distance between two points using the distance()
method.
A8: The distance() method would take the coordinates of another point and use the distance
formula to calculate the distance between the two points. The formula is sqrt((x2 - x1)2 + (y2 - y1)2).
5. Shape Hierarchy
A9: Polymorphism in Java allows objects of different types to be treated as objects of a common
superclass. In the Shape hierarchy, polymorphism is demonstrated when you can call draw() and
erase() on objects of different subclasses (circle, triangle, square), and they behave differently
based on their specific implementations.
Q10: Describe the methods draw() and erase() in the Shape subclasses.
A10: In the Shape subclasses, draw() would typically output a message or perform an action to
visually represent the shape being drawn, while erase() would do the opposite, representing the
action of erasing the shape.
Q11: What is an abstract class in Java? How is it different from a regular class?
A11: An abstract class is a class that cannot be instantiated directly; it serves as a blueprint for
other classes. It may contain abstract methods (methods without implementation) that must be
overridden by its subclasses. A regular class can be instantiated directly.
Q12: How would you implement the calculateArea() and calculatePerimeter() methods in the Circle
and Triangle subclasses?
A12: In the Circle subclass, calculateArea() would use the formula pi * radius^2 to calculate the area,
and calculatePerimeter() would use 2 * pi * radius to calculate the perimeter. In the Triangle subclass,
you would use the appropriate formulas for area and perimeter based on the type of triangle.
7. Resizable Interface
Q14: How would you implement the resizeWidth() and resizeHeight() methods in a class that
implements the Resizable interface?
A14: In a class that implements the Resizable interface, resizeWidth(int width) and resizeHeight(int
height) would adjust the object's width and height according to the specified parameters.
Q15: What is an inner class in Java? How is it different from an outer class?
A15: An inner class is a class defined within another class. It has access to all members of the
outer class, including private members. Inner classes have a direct reference to the instance of
the outer class. Outer classes, on the other hand, are not defined within any other class.
Q16: Explain how you would call functions from both the outer and inner classes.
A16: To call a function from the inner class, you would first need to create an instance of the
outer class. Then, you can create an instance of the inner class and call its function using the
outer class instance as a reference.
Q18: How would you use try, catch, throw, and finally to handle a custom exception for
DivisionByZero?
A18: You would use a try block to enclose the code that might throw the custom exception. If the
exception occurs, you can use a catch block to handle it. Inside the catch block, you can use the
throw keyword to explicitly throw the custom exception. The finally block can be used to execute
code that should run regardless of whether an exception was thrown.
Q20: How would you import and implement a package named mypack in a suitable class?
A20: To import the mypack package, you would include the statement import mypack.*; at the
beginning of your Java file. Then, you can use the classes and other elements from the mypack
package in your program.
Q21: Explain the difference between extending Thread class and implementing Runnable
interface for creating threads.
A21: When you extend the Thread class, your class cannot extend any other class as Java doesn't
support multiple inheritance. However, when you implement the Runnable interface, you can still
extend other classes. Implementing Runnable is generally considered a better practice because it
separates the task from the thread, allowing for better code organization and reusability.
Q22: How would you create threads using the Runnable interface? Describe the steps involved.
A22: To create threads using the Runnable interface, you would follow these steps:
Example:
Q23: How would you create a class MyThread that extends the Thread class?
A23: To create a class MyThread that extends the Thread class, you would define a class that
inherits from Thread and override the run() method with your custom code.
Q24: Explain how both the main thread and the child thread execute concurrently.
A24: When you create and start a Thread object, it begins executing the run() method in a separate
execution context. This means that both the main thread (which starts the child thread) and the
child thread run concurrently, performing their respective tasks independently of each other. The
operating system manages the scheduling and execution of threads.
Example:
Vision
Creating an excellent educational institution which educates in
the domains of computer science and engineering and
successfully serving community and industrial demands.
Mission
✓Through the implementation of outcome-oriented methods of
instruction to enhance learner’s technical competency across a
variety of computer science and engineering fields.
✓To offer graduates with the abilities required to operate
professionally as efficient individuals.
✓To motivate the advancement of university academics and
industry association.
✓To promote knowledge regarding possibilities through
enterprise.