0% found this document useful (0 votes)
4 views38 pages

Java Lab Manual III Sem 23

The document is a lab manual for the Object Oriented Programming with Java course at Mysuru Royal Institute of Technology, detailing experiments and practicals for III Semester B.E. CSE students. It includes instructions for various programming tasks, such as matrix addition, stack operations, employee management, and point distance calculations, along with grading criteria for lab performance. Each section provides code examples and expected outputs to guide students in completing their assignments.

Uploaded by

sariyaanjum8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

Java Lab Manual III Sem 23

The document is a lab manual for the Object Oriented Programming with Java course at Mysuru Royal Institute of Technology, detailing experiments and practicals for III Semester B.E. CSE students. It includes instructions for various programming tasks, such as matrix addition, stack operations, employee management, and point distance calculations, along with grading criteria for lab performance. Each section provides code examples and expected outputs to guide students in completing their assignments.

Uploaded by

sariyaanjum8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

MYSURU ROYAL INSTITUTE OF TECHNOLOGY

(Approved by AICTE, New Delhi, Affiliated to VTU, Belagavi,)


Lakshmipura Road, Palahalli Post, Srirangapatna, Mandya - 571606

MRIT

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

OBJECTED ORIENTED PROGRAMMING WITH JAVA


LAB MANUAL
III Semester B.E. CSE
Course Code: BCS306A

Student Name :. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Branch : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Semester : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Section : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Roll. No. : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

USN. : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Faculty Name : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


...

Mr. Chethan Raj C


Assistant Professor & HoD,
Department of Computer Science, MRIT, Mandya
Name: Section: USN:
B.E. III Sem Object Oriented
Course Stream : CSE Course Code : BCS306A
Programming with Java Lab
Distribution of Marks for Conduction of Experiments and Record for CIE

Sl. Conduction Result Viva Record Total


Date Experiment Name
No. 15 Marks 10 Marks 5 Marks 20 Marks 50 Marks

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]

Distribution of Marks for conduction of Laboratory Test for CIE


Sl. Write up Conduction Result Viva Total
Date Experiment Name
No. 10 Marks 25 Marks 5 Marks 10 Marks 50 Marks

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

Signature of the Faculty Signature of the HoD with Seal


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should
be read from command line arguments).
Save Filename as: MatrixAddition.java
Solution:-
public class MatrixAddition
{
public static void main (String[] args)
{
int n = Integer.parseInt (args[0]);
int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] sum = new int[n][n];
// Initialize matrices with some values, for example, i+j
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
matrix1[i][j] = i + j;
matrix2[i][j] = i + j;
}
}
// Add the matrices
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Print the result
System.out.println ("Sum of matrices is: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print (sum[i][j] + " ");
}
System.out.println ();
}
}
}
Compile as: javacMatrixAddition.java
Run as: java MatrixAddition 3

Output:
Sum of matrices is:
0 2 4
2 4 6
6 8 7

Dept. of CSE, MRIT, MANDYA Page 1


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations
Save Filename as:StackMain.java
Solution:-
import java.util.Scanner;
class Stack
{
private int maxSize = 10;
private int top;
private int[] stackArray;
public Stack ()
{
stackArray = new int[maxSize];
top = -1;
}

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++)
{

Dept. of CSE, MRIT, MANDYA Page 2


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
System.out.print (stackArray[i] + " ");
}
System.out.println ();
}
}
public class StackMain
{
public static void main (String[] args)
{
Stack stack = new Stack ();
Scanner scanner = new Scanner (System.in);
while (true)
{
System.out.println ("Choose an option:");
System.out.println ("1) Push");
System.out.println ("2) Pop");
System.out.println ("3) Display");
System.out.println ("4) Exit");
int option = scanner.nextInt ();
switch (option)
{
case 1:
System.out.println ("Enter a number to push:");
int num = scanner.nextInt ();
stack.push (num);
break;

case 2:
stack.pop ();
break;

case 3:
stack.display ();
break;

case 4:
scanner.close ();
return;

default:
System.out.println("Invalid option.Please
choose again.");
}
}
}
}

Dept. of CSE, MRIT, MANDYA Page 3


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
Compile As: javacStackMain.java
Run As: java StackMain

Output:
Choose an option:
1) Push
2) Pop
3) Display
4) Exit

Enter a number to push:


10
Choose an option:
1) Push
2) Pop
3) Display
4) Exit

Enter a number to push:


20
Choose an option:
1) Push
2) Pop
3) Display
4) Exit

Enter a number to push:


30
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

Popped 30 from the stack


Choose an option:
1) Push
2) Pop
3) Display
4) Exit

Stack: 10 20

Dept. of CSE, MRIT, MANDYA Page 4


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
Choose an option:
1) Push
2) Pop
3) Display
4) Exit

Dept. of CSE, MRIT, MANDYA Page 5


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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.
Save Filename as as: EmployeeMain.java
Solution:-
import java.util.Scanner;
class Employee
{
private int id;
private String name;
private double salary;
public Employee (int id, String name, double salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public int
getId ()
{
return id;
}
public String
getName ()
{
return name;
}
public double
getSalary ()
{
return salary;
}
public void
raiseSalary (double percent)
{
salary += salary * percent / 100.0;
}
}
public class EmployeeMain
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
System.out.println ("Enter Employee ID:");
int id = scanner.nextInt ();
System.out.println ("Enter Employee Name:");
scanner.nextLine (); // Consume newline left-over
String name = scanner.nextLine ();

Dept. of CSE, MRIT, MANDYA Page 6


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
System.out.println ("Enter Employee Salary:");
double salary = scanner.nextDouble ();
Employee emp = new Employee (id, name, salary);
System.out.println ("Employee ID: " + emp.getId ());
System.out.println ("Employee Name: " + emp.getName ());
System.out.println ("Employee Salary: " + emp.getSalary ());
System.out.println ("Enter raise percentage:");
double percent = scanner.nextDouble ();
emp.raiseSalary (percent);
System.out.println ("Employee Salary after raise: " +
emp.getSalary ());
scanner.close ();
}
}

Compile As: javacEmployeeMain.java


Run As: java EmployeeMain

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

Dept. of CSE, MRIT, MANDYA Page 7


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE

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.

Save Filename As: TestMyPoint.java


Solution:-
class MyPoint
{
private int x;
private int y;

// 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 };

Dept. of CSE, MRIT, MANDYA Page 8


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
return coordinates;
}

// Calculate distance to another point (x, y)


public double
distance (int x, int y)
{
return Math.sqrt (Math.pow (this.x - x, 2) + Math.pow (this.y
- y, 2));
}

// Calculate distance to another MyPoint object


public double
distance (MyPoint another)
{
return Math.sqrt (Math.pow (this.x - another.x, 2)
+ Math.pow (this.y - another.y, 2));
}

// Calculate distance to the origin (0,0)


public double
distance ()
{
return Math.sqrt (Math.pow (this.x, 2) + Math.pow (this.y,
2));
}

// String representation of the point


@Override
public String
toString ()
{
return "(" + x + ", " + y + ")";
}
}

public class TestMyPoint


{
public static void main (String[] args)
{
MyPoint point1 = new MyPoint (); // Default constructor
MyPoint point2 = new MyPoint (3, 4); // Overloaded
constructor point1.setXY (5, 6); // Set x and y

int[] coordinates = point2.getXY (); // Get x and y

System.out.println ("Point 1: " + point1);


System.out.println ("Point 2: " + point2);

Dept. of CSE, MRIT, MANDYA Page 9


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
System.out.println ("Point 2 coordinates: (" + coordinates[0]
+ ", "
+ coordinates[1] + ")");
System.out.println ("Distance from Point 1 to (5, 6): "
+ point2.distance (point1));
System.out.println("Distance from Point 2 to Point 1: " +
System.out.println("Distance from Point 2 to origin: " +
point2.distance());
}
}

Compile As: javacTestMyPoint.java


Run As: java TestMyPoint

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

Dept. of CSE, MRIT, MANDYA Page 10


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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
Save Filename as: ShapeMain.java
Solution:-
class Shape
{
public void
draw ()
{
System.out.println ("Drawing a shape");
}

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 ()
{

Dept. of CSE, MRIT, MANDYA Page 11


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
System.out.println ("Erasing a triangle");
}
}

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 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
}
}
}

Compile As: javacShapeMain.java


Run As: java ShapeMain

Output:
Drawing a circle
Erasing a circle

Drawing a triangle
Erasing a triangle

Drawing a square
Erasing a square

Dept. of CSE, MRIT, MANDYA Page 12


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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.
Save Filename as: Shape_peri_area_Main.java
Solution:-
abstract class Shape
{
// Abstract methods to calculate area and perimeter
public abstract double calculateArea ();
public abstract double calculatePerimeter ();
}
class Circle extends Shape
{
private double radius;

// 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

Dept. of CSE, MRIT, MANDYA Page 13


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
calculateArea ()
{
double s = (side1 + side2 + side3) / 2;
return Math.sqrt (s * (s - side1) * (s - side2) * (s –
side3));
}

@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 ());
}
}

Compile As: javacShape_peri_area_Main.java


Run As: java Shape_peri_area_Main

Output:
Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793

Triangle:
Area: 6.0
Perimeter: 12.0

Dept. of CSE, MRIT, MANDYA Page 14


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
7. D evelop 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.
Save Filename as: rect_resize.java
Solution:-
interface Resizable
{
void resizeWidth (int width);
void resizeHeight (int height);
}

class Rectangle implements Resizable


{
private int width;
private int height;

// 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;
}

// Additional method to get the dimensions


public void
getDimensions ()
{
System.out.println ("Width: " + width + ", Height: " +
height);
}
}

public class rect_resize


{
public static void main (String[] args)

Dept. of CSE, MRIT, MANDYA Page 15


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
{
Rectangle rectangle = new Rectangle (5, 7);

System.out.println ("Original Dimensions:");


rectangle.getDimensions ();

rectangle.resizeWidth (8);
rectangle.resizeHeight (10);

System.out.println ("\nResized Dimensions:");


rectangle.getDimensions ();
}
}

Compile As: javacrect_resize.java


Run As: java rect_resize

Output:
Original Dimensions:
Width: 5, Height: 7

Resized Dimensions:
Width: 8, Height: 10

Dept. of CSE, MRIT, MANDYA Page 16


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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.
Save Filename As: InnerOuter.java
Solution:-
class Outer
{
void display()
{
System.out.println("Outer display");
}

class Inner
{
void display()
{
System.out.println("Inner display");
}
}
}

public class InnerOuter


{
public static void main(String[] args)
{
Outer outer = new Outer();
Outer.Inner inner = outer.newInner();
outer.display(); // Calls the outer class display()
function
inner.display(); // Calls the inner class display()
function
}
}

Compile As: javacInnerOuter.java


Run As: java InnerOuter

Output:
Outer display
Inner display

Dept. of CSE, MRIT, MANDYA Page 17


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally
Save Filename As: CustomException.java
Solution:-
// Custom Exception Class
class DivisionByZeroException extends Exception
{
public DivisionByZeroException (String message) { super
(message); }
}
public class CustomException
{
public static void main (String[] args)
{
int dividend = 10;
int divisor = 0;
try
{
if (divisor == 0)
{
throw new DivisionByZeroException("Cannot divide
by zero");
}
int result = dividend / divisor;
System.out.println ("Result: " + result);
}
catch (DivisionByZeroException e)
{
System.out.println ("Exception: " + e.getMessage ());
}
finally
{
System.out.println ("Finally block executed");
}
}
}

Compile As: javacCustomException.java


Run As: java CustomException

Output:
Exception: Cannot divide by zero
Finally block executed

Dept. of CSE, MRIT, MANDYA Page 18


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
10. Develop a JAVA program to create a package named mypack and import & implement it
in a suitable class
Step 1: Create a Package
Create a directory named mypack (or any name you prefer) on your file system. Inside the
mypack directory, create a Java file named MyClass.java.

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.");
}
}

Step 3: Create a Main Program


Create a new Java file (outside the mypack directory) named MainProgram.java and add the
following code:

import mypack.MyClass;

public class MainProgram


{
public static void main (String[] args)
{
MyClass obj = new MyClass ();
obj.display ();
}
}

Step 4: Compile and Run


Open a terminal or command prompt and navigate to the directory containing both the mypack
directory and MainProgram.java.

Compile both files using the following command:


javacmypack/MyClass.java MainProgram.java

Run the program with the command:


java MainProgram

Output:
This is a method from the mypack package.

Dept. of CSE, MRIT, MANDYA Page 19


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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)
Save Filename as: ThreadMain.java
Solution:-
class MyRunnable implements Runnable
{
@Override
public void run()
{
Try
{
System.out.println("Thread " +
Thread.currentThread().getId() + " is running.");
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted: " +
e.getMessage());
}
}
}

public class ThreadMain


{
public static void main(String[] args)
{
int numThreads = 5;
for (int i = 0; i<numThreads; i++)
{
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
}

Compile As: javacThreadMain.java


Run As: java ThreadMain

Output:
Thread 10 is running.
Thread 12 is running.
Thread 14 is running.
Thread 13 is running.
Thread 11 is running.

Dept. of CSE, MRIT, MANDYA Page 20


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
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.
Save Filename as: ThreadConstructor.java
Solution:-
class MyThread extends Thread
{
MyThread (String name)
{
super (name); // Call the base class constructor with thread
name start (); // Start the thread
}

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.");
}
}

public class ThreadConstructor


{
public static void main (String[] args)
{
new MyThread ("Child Thread");

try
{
for (int i = 5; i > 0; i--)
{
System.out.println ("Main Thread: " + i);
Thread.sleep (2000);
}
}

catch (InterruptedException e)

Dept. of CSE, MRIT, MANDYA Page 21


OOPS With JAVA Laboratory (BCS306A) DEPARTMENT OF CSE
{
System.out.println ("Main Thread interrupted.");
}
System.out.println ("Main Thread exiting.");
}
}

Compile As: javacThreadConstructor.java


Run As: java ThreadConstructor

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.

Dept. of CSE, MRIT, MANDYA Page 22


Viva questions and answers
1. Object-Oriented Programming Concepts:

Q1: What is Object-Oriented Programming (OOP)?

A1: Object-Oriented Programming is a programming paradigm based on the concept of


"objects", which are instances of classes. It focuses on organizing code into reusable, self-
contained objects with defined behaviors and attributes.

Q2: Name the four main principles of OOP.

A2: The four main principles of OOP are:

• Encapsulation
• Inheritance
• Polymorphism
• Abstraction

Q3: Explain encapsulation.

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.

Q4: What is inheritance in OOP?

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.

Q5: Describe polymorphism.

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.

Q6: Explain abstraction.

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.

Q8: What is the difference between JDK and JRE?

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.

Q9: What is a class in Java?

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.

Q10: What is an object in Java?

A10: An object is an instance of a class. It is a real-world entity with a unique identity, state
(attributes), and behavior (methods).

Q11: How do you declare a variable in Java?

A11: You can declare a variable in Java using the syntax: datatype variableName; For
example: int age;

3. Control Statements and Loops:

Q12: Explain the if-else statement in Java.

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.

Q13: What is a switch statement?

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.

Q14: Describe a for loop in Java.

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.

Q16: What is the purpose of a do-while loop?

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.

4. Arrays and Collections:

Q17: How do you declare an array in Java?

A17: You can declare an array in Java using the syntax: datatype[] arrayName; For example:
int[] numbers;

Q18: Explain the difference between an array and an ArrayList.

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.

Q19: What is the purpose of the List interface in Java?

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.

Q20: What is the difference between a Set and a List in Java?

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:

Q21: What is an exception in Java?

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.

Q22: How do you handle exceptions in Java?


A22: Exceptions in Java can be handled using try-catch blocks. The code that may throw an
exception is placed in the try block, and if an exception occurs, it is caught and handled in the
catch block.

Q23: What is the purpose of the finally block in exception handling?

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.

Q24: What is the difference between checked and unchecked exceptions?

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.

6. Threads and Concurrency:

Q25: What is a thread in Java?

A25: A thread is the smallest unit of execution within a process. It allows a program to perform
tasks concurrently and asynchronously.

Q26: How can you create a thread in Java?

A26: There are two ways to create a thread in Java:

• By extending the Thread class.


• By implementing the Runnable interface.

Q27: What is synchronization in Java?

A27: Synchronization in Java is a technique used to control access to shared resources by


multiple threads. It ensures that only one thread can execute a synchronized block of code at a
time.

Q28: Explain the difference between wait() and sleep() in Java.

A28: wait() is a method in the Object class that causes the current thread to wait until another
thread invokes the notify() or `notify

Q28: Explain the difference between wait() and sleep() in Java.

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:

Q29: How do you read from a file in Java?

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.

Q30: Explain the difference between File and FileInputStream.

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.

8. Packages and Imports:

Q31: What is a package in Java?

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.

Q32: How do you import classes from a package in Java?

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.

Q33: What is the default package in Java?

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.

9. Interfaces and Abstract Classes:

Q34: What is an interface in Java?

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.

Q35: Can a class implement multiple interfaces in Java?


A35: Yes, a class can implement multiple interfaces in Java. This allows the class to inherit the
abstract methods from multiple sources.

Q36: What is the purpose of an abstract class in Java?

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.

Q37: Can an abstract class have non-abstract methods?

A37: Yes, an abstract class can have both abstract and non-abstract (concrete) methods. It may
also have attributes and constructors.

10. Inheritance and Polymorphism:

Q38: Explain method overriding in Java.

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.

Q39: What is the difference between super and this in Java?

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.

Q40: How does dynamic polymorphism work in Java?

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.

11. Lambda Expressions and Streams:

Q41: What is a lambda expression in Java?

A41: A lambda expression is a concise way to represent an anonymous function. It provides a


way to pass functions as arguments or return them as values from methods.

Q42: What is a Stream in Java 8+?

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.

12. Annotations and Reflection:

Q44: What is an annotation in Java?

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.

Q45: What is reflection in Java?

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.

Q46: Can you give an example of an annotation in Java?

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");
}
}

class Child extends Parent {


@Override
public void display() {
System.out.println("Child class");
}
}

13. Serialization and Deserialization:

Q47: What is object serialization in Java?

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.

Q48: How do you make a class serializable in Java?


A48: To make a class serializable in Java, it must implement the Serializable interface. This is
a marker interface that does not contain any methods.

import java.io.Serializable;

class MyClass implements Serializable {


// Class implementation
}

Q49: What is the purpose of serialVersionUID in serialization?

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.

14. Design Patterns:

Q50: What is the Singleton design pattern?

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

Q3: Describe the basic operations performed on a stack.

A3: The basic operations on a stack are:

• Push: Adds an element to the top of the stack.


• Pop: Removes and returns the element from the top of the stack.
• Peek (or Top): Returns the element from the top of the stack without removing it.
• isEmpty: Checks if the stack is empty.

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.

Q6: How would you implement the raiseSalary() method in Java?

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

Q7: Describe the attributes of the 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

Q9: What is polymorphism in Java? How is it demonstrated in the 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.

6. Abstract Class and Subclasses

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

Q13: Explain the purpose of the Resizable interface.


A13: The Resizable interface defines methods (resizeWidth(int width) and resizeHeight(int height)) that
allow an object to be resized. Classes that implement this interface can adjust their dimensions
based on specific requirements.

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.

8. Outer and Inner Classes

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.

9. Custom Exception Handling

Q17: What is a custom exception in Java?

A17: A custom exception (user-defined exception) is an exception that is defined by the


programmer to handle specific situations that may not be covered by the built-in exceptions in
Java.

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.

10. Creating and Using Packages

Q19: What is a Java package?


A19: A Java package is a way to organize related classes, interfaces, and sub-packages in a
hierarchical structure. It helps avoid naming conflicts and provides a clear organizational
structure for large projects.

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.

11. Thread Creation using Runnable

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:

1. Create a class that implements the Runnable interface.


2. Implement the run() method, which contains the code that will be executed by the thread.
3. Instantiate an object of your class.
4. Create a Thread object, passing your class instance as an argument to the constructor.
5. Call the start() method on the Thread object to begin execution.

Example:

class MyRunnable implements Runnable {


public void run() {
// Code to be executed by the thread
}
}

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}

12. Concurrent Execution with MyThread

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:

class MyThread extends Thread {


public void run() {
// Code to be executed by the thread
}
}

public class Main {


public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // Starts the child thread
// Code in the main thread continues to execute concurrently with the
child thread
}
}
OOPS WITH JAVA LAB
Department of the Computer
Science & Engineering

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.

You might also like