Java Programming – Lab Assignment
Unit 2 | Unit 3 | Unit 4
======================================================================
=== Unit 2 ===
Q1. Single Inheritance – Birds and Parrot
class Birds
{
void sound() {
[Link]("Birds make sound");
}
}
class Parrot extends Birds {
void speak() {
[Link]("Parrot says: Hello!");
}
}
public class SingleInheritance {
public static void main(String[] args) {
Parrot p = new Parrot();
[Link]();
[Link]();
}
}
C:\JavaPrograms>javac [Link]
C:\JavaPrograms>java SingleInheritance
Birds make sound
Parrot says: Hello!
Q2. Multilevel Inheritance – Student, College, University
class University
{
void uniName() {
[Link]("University: Mumbai University");
}
}
class College extends University {
void collegeName() {
[Link]("College: ABC Engineering College");
}
}
class Student extends College {
void studentName() {
[Link]("Student: Rahul Sharma");
}
}
public class MultilevelInheritance {
public static void main(String[] args) {
Student s = new Student();
[Link]();
[Link]();
[Link]();
}
}
C:\JavaPrograms>javac [Link]
C:\JavaPrograms>java MultilevelInheritance
University: Mumbai University
College: ABC Engineering College
Student: Rahul Sharma
Q3. Hierarchical Inheritance – Shape, Circle, Rectangle
class Shape
{
void display() {
[Link]("This is a Shape");
}
}
class Circle extends Shape {
void area() {
double r = 5;
[Link]("Area of Circle: " + (3.14 * r * r));
}
}
class Rectangle extends Shape {
void area() {
[Link]("Area of Rectangle: " + (10 * 4));
}
}
public class HierarchicalInheritance {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
Rectangle r = new Rectangle();
[Link]();
[Link]();
}
}
C:\JavaPrograms>java HierarchicalInheritance
This is a Shape
Area of Circle: 78.5
This is a Shape
Area of Rectangle: 40
Q4. super Keyword – Calling Parent Constructor
class Animal
{
String name;
Animal(String name) {
[Link] = name;
[Link]("Animal Constructor called: " + name);
}
}
class Dog extends Animal
{
String breed;
Dog(String name, String breed) {
super(name);
[Link] = breed;
[Link]("Dog Constructor called");
[Link]("Name: " + name + ", Breed: " + breed);
}
}
public class SuperKeyword {
public static void main(String[] args) {
Dog d = new Dog("Tommy", "Labrador");
}
}
C:\JavaPrograms>java SuperKeyword
Animal Constructor called: Tommy
Dog Constructor called
Name: Tommy, Breed: Labrador
Q5. Method Overloading – add() with Different Parameter
public class MethodOverloading
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MethodOverloading obj = new MethodOverloading();
[Link]("add(10, 20) = " + [Link](10, 20));
[Link]("add(10, 20, 30) = " + [Link](10, 20, 30));
[Link]("add(1.5, 2.5) = " + [Link](1.5, 2.5));
}
}
C:\JavaPrograms>java MethodOverloading
add(10, 20) = 30
add(10, 20, 30) = 60
add(1.5, 2.5) = 4.0
Q6. Method Overriding
class Vehicle
{
void run() {
[Link]("Vehicle is running");
}
}
class Car extends Vehicle {
@Override
void run() {
[Link]("Car is running at 120 km/h");
}
}
public class MethodOverriding {
public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link]();
Car c = new Car();
[Link]();
Vehicle vc = new Car();
[Link]();
}
}
C:\JavaPrograms>java MethodOverriding
Vehicle is running
Car is running at 120 km/h
Car is running at 120 km/h
Q7. Constructor Overloading
public class ConstructorOverloading
{
int length, width, height;
ConstructorOverloading() {
length = width = height = 0;
[Link]("Default: l=0, w=0, h=0");
}
ConstructorOverloading(int l, int w) {
length = l; width = w; height = 1;
[Link]("2-arg: l=" + l + ", w=" + w + ", h=1");
}
ConstructorOverloading(int l, int w, int h) {
length = l; width = w; height = h;
[Link]("3-arg: l=" + l + ", w=" + w + ", h=" + h);
}
public static void main(String[] args) {
ConstructorOverloading o1 = new ConstructorOverloading();
ConstructorOverloading o2 = new ConstructorOverloading(5, 3);
ConstructorOverloading o3 = new ConstructorOverloading(4, 6, 2);
}
}
C:\JavaPrograms>java ConstructorOverloading
Default: l=0, w=0, h=0
2-arg: l=5, w=3, h=1
3-arg: l=4, w=6, h=2
Q8. Abstract Class with Abstract Method
abstract class Shape
{
abstract void draw();
void color() {
[Link]("Color: Red");
}
}
class Circle extends Shape {
@Override
void draw() {
[Link]("Drawing Circle");
}
}
class Triangle extends Shape {
@Override
void draw() {
[Link]("Drawing Triangle");
}
}
public class AbstractClassDemo {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
Triangle t = new Triangle();
[Link]();
[Link]();
}
}
C:\JavaPrograms>java AbstractClassDemo
Drawing Circle
Color: Red
Drawing Triangle
Color: Red
Q9. Abstract Class with Constructor
abstract class Employee
{
String name;
int salary;
Employee(String name, int salary) {
[Link] = name;
[Link] = salary;
[Link]("Employee constructor called");
}
abstract void display();
}
class Manager extends Employee {
String department;
Manager(String name, int salary, String dept) {
super(name, salary); // calls abstract class constructor
[Link] = dept;
}
@Override
void display() {
[Link]("Name: " + name);
[Link]("Salary: " + salary);
[Link]("Department: " + department);
}
}
public class AbstractConstructor {
public static void main(String[] args) {
Manager m = new Manager("Amit", 75000, "IT");
[Link]();
}
}
C:\JavaPrograms>java AbstractConstructor
Employee constructor called
Name: Amit
Salary: 75000
Department: IT
Q10. Interface Implementation
interface Printable
{
void print();
}
class Document implements Printable {
@Override
public void print() {
[Link]("Printing Document...");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Document d = new Document();
[Link]();
// Using interface reference
Printable p = new Document();
[Link]();
}
}
C:\JavaPrograms>java InterfaceDemo
Printing Document...
Printing Document...
Q11. Same Interface Implemented in Multiple Classes
interface Drawable
{
void draw();
}
class Circle implements Drawable {
public void draw() {
[Link]("Drawing Circle");
}
}
class Square implements Drawable {
public void draw() {
[Link]("Drawing Square");
}
}
class Triangle implements Drawable {
public void draw() {
[Link]("Drawing Triangle");
}
}
public class MultipleClassInterface {
public static void main(String[] args) {
Drawable d1 = new Circle();
Drawable d2 = new Square();
Drawable d3 = new Triangle();
[Link]();
[Link]();
[Link]();
}
}
C:\JavaPrograms>java MultipleClassInterface
Drawing Circle
Drawing Square
Drawing Triangle
Q12. Multiple Inheritance using Interfaces
interface Flyable
{
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() {
[Link]("Duck can fly");
}
public void swim() {
[Link]("Duck can swim");
}
}
public class MultipleInheritanceInterface {
public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}
C:\JavaPrograms>java MultipleInheritanceInterface
Duck can fly
Duck can swim
Q13. User-Defined Package – Define a Class
▶ Java Program:
package mypackage;
public class Student
{
public String name;
public int rollNo;
public Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
public void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}
}
■ Output (Command Prompt Screenshot Simulation):
C:\JavaPrograms>javac -d . [Link]
C:\JavaPrograms>_
Q14. Import and Use a User-Defined Package
import [Link];
public class UsePackage
{
public static void main(String[] args) {
Student s = new Student("Riya", 101);
[Link]();
}
}
C:\JavaPrograms>javac [Link]
C:\JavaPrograms>java UsePackage
Roll No: 101
Name: Riya
Q15. Package with Addition Class
package mathpkg;
public class Addition
{
public int add(int a, int b) {
return a + b;
}
}
// File: [Link]
import [Link];
public class TestAddition {
public static void main(String[] args) {
Addition obj = new Addition();
int result = [Link](25, 35);
[Link]("Sum = " + result);
}
}
■ Output (Command Prompt Screenshot Simulation):
C:\JavaPrograms>java TestAddition
Sum = 60
Q16. Package for Multiplication using Classpath
package multpkg;
public class Multiply
{
public int multiply(int a, int b) {
return a * b;
}
}
// File: [Link]
import [Link];
public class TestMultiply {
public static void main(String[] args) {
Multiply m = new Multiply();
[Link]("Product = " + [Link](6, 7));
}
}
C:\JavaPrograms>javac -d . [Link]
C:\JavaPrograms>java TestMultiply
Product = 42
=== Unit 3 ===
Q1. try and catch – Division by Zero
▶ Java Program:
public class TryCatchDemo {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]("Program continues...");
}
}
C:\JavaPrograms>java TryCatchDemo
Exception caught: / by zero
Program continues...
Q2. Multiple catch Blocks
▶ Java Program:
public class MultipleCatch
{
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 100;
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Exception: " + [Link]());
} catch (Exception e) {
[Link]("General Exception: " + [Link]());
}
[Link]("After try-catch block");
}
}
C:\JavaPrograms>java MultipleCatch
Array Index Exception: Index 10 out of bounds for length 5
After try-catch block
Q3. finally Block
public class FinallyDemo
{
public static void main(String[] args) {
try {
[Link]("Inside try block");
int result = 10 / 2;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("finally block always executes");
}
[Link]("--- Second example ---");
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("finally executes even after exception");
}
}
}
C:\JavaPrograms>java FinallyDemo
Inside try block
Result: 5
finally block always executes
--- Second example ---
Exception caught: / by zero
finally executes even after exception
Q4. Nested try Statements
public class NestedTry
{
public static void main(String[] args) {
try {
[Link]("Outer try block");
try {
[Link]("Inner try block");
int[] arr = new int[3];
arr[5] = 10; // throws exception
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: " + [Link]());
}
int x = 10 / 0; // outer exception
} catch (ArithmeticException e) {
[Link]("Outer catch: " + [Link]());
} finally {
[Link]("Outer finally block");
}
}
}
C:\JavaPrograms>java NestedTry
Outer try block
Inner try block
Inner catch: Index 5 out of bounds for length 3
Outer catch: / by zero
Outer finally block
Q5. User-Defined Exception – Voting Eligibility
class InvalidAgeException extends Exception
{
public InvalidAgeException(String message) {
super(message);
}
}
public class VotingEligibility {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is invalid for
voting!");
} else {
[Link]("Age " + age + ": Eligible to vote.");
}
}
public static void main(String[] args) {
try {
checkAge(20);
checkAge(15);
} catch (InvalidAgeException e) {
[Link]("Caught: " + [Link]());
}
}
}
C:\JavaPrograms>java VotingEligibility
Age 20: Eligible to vote.
Caught: Age 15 is invalid for voting!
Q6. throw and throws Keyword
public class ThrowThrows
static void validateMarks(int marks) throws IllegalArgumentException {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Invalid marks: " + marks);
}
[Link]("Marks are valid: " + marks);
}
public static void main(String[] args) {
try {
validateMarks(85);
validateMarks(110); // will throw
} catch (IllegalArgumentException e) {
[Link]("Exception: " + [Link]());
}
}
}
C:\JavaPrograms>java ThrowThrows
Marks are valid: 85
Exception: Invalid marks: 110
Q7. Thread by Extending Thread Class
▶ Java Program:
class MyThread extends Thread
{
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread running: " + i);
try { [Link](300); }
catch (InterruptedException e) { [Link](); }
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
[Link]("Main thread continues...");
}
}
C:\JavaPrograms>java ThreadDemo
Main thread continues...
Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5
Q8. Thread by Implementing Runnable Interface
class MyRunnable implements Runnable
{
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Runnable thread: " + i);
try { [Link](300); }
catch (InterruptedException e) { [Link](); }
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
[Link]();
[Link]("Main thread...");
}
}
C:\JavaPrograms>java RunnableDemo
Main thread...
Runnable thread: 1
Runnable thread: 2
Runnable thread: 3
Runnable thread: 4
Runnable thread: 5
Q9. Thread Synchronization using synchronized Method
class Counter
{
private int count = 0;
synchronized void increment() {
count++;
[Link]([Link]().getName()
+ " -> Count: " + count);
}
}
class Worker extends Thread {
Counter c;
Worker(Counter c, String name) {
super(name);
this.c = c;
}
public void run() {
for (int i = 0; i < 3; i++) [Link]();
}
}
public class SynchronizationDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Worker t1 = new Worker(c, "Thread-1");
Worker t2 = new Worker(c, "Thread-2");
[Link](); [Link]();
[Link](); [Link]();
[Link]("Final Count: " + [Link]);
}
}
C:\JavaPrograms>java SynchronizationDemo
Thread-1 -> Count: 1
Thread-1 -> Count: 2
Thread-1 -> Count: 3
Thread-2 -> Count: 4
Thread-2 -> Count: 5
Thread-2 -> Count: 6
Final Count: 6
Q10. Inter-Thread Communication – wait(), notify(), notifyAll()
class SharedResource
{
int data;
boolean produced = false;
synchronized void produce(int value) throws InterruptedException {
while (produced) wait();
data = value;
[Link]("Produced: " + data);
produced = true;
notify();
}
synchronized void consume() throws InterruptedException {
while (!produced) wait();
[Link]("Consumed: " + data);
produced = false;
notify();
}
}
public class InterThreadComm {
public static void main(String[] args) {
SharedResource r = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
try { [Link](i); } catch (InterruptedException e) {}
}
});
Thread consumer = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
try { [Link](); } catch (InterruptedException e) {}
}
});
[Link]();
[Link]();
}
}
C:\JavaPrograms>java InterThreadComm
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
=== Unit 4 ===
Q1. Read Data from Keyboard using BufferedReader
import [Link].*;
public class BufferedReaderDemo
{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]([Link]());
[Link]("Name: " + name + ", Age: " + age);
}
}
C:\JavaPrograms>java BufferedReaderDemo
Enter your name: Rahul
Enter your age: 21
Name: Rahul, Age: 21
Q2. User Input using Scanner – Arithmetic Operations
import [Link];
public class ScannerArithmetic
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
double a = [Link]();
[Link]("Enter second number: ");
double b = [Link]();
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
if (b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Division: Cannot divide by zero");
[Link]();
}
}
C:\JavaPrograms>java ScannerArithmetic
Enter first number: 10
Enter second number: 4
Addition: 14.0
Subtraction: 6.0
Multiplication: 40.0
Division: 2.5
Q3. User-Defined Package – Access in Another Class
package utilities;
public class MathUtils
{
public int square(int n) { return n * n; }
public int cube(int n) { return n * n * n; }
}
// File: [Link]
import [Link];
public class TestMathUtils {
public static void main(String[] args) {
MathUtils m = new MathUtils();
[Link]("Square of 5: " + [Link](5));
[Link]("Cube of 3: " + [Link](3));
}
}
C:\JavaPrograms>javac -d . [Link]
C:\JavaPrograms>java TestMathUtils
Square of 5: 25
Cube of 3: 27
Q4. Predefined Packages – [Link] and [Link]
import [Link];
import [Link];
import [Link];
public class PredefinedPackages
{
public static void main(String[] args) {
// [Link] - ArrayList
ArrayList<String> list = new ArrayList<>();
[Link]("Java"); [Link]("Python"); [Link]("C++");
[Link]("Languages: " + list);
// [Link] - Date
Date d = new Date();
[Link]("Current Date: " + d);
// [Link] - File
File f = new File("[Link]");
[Link]("File name: " + [Link]());
[Link]("Absolute path: " + [Link]());
}
}
C:\JavaPrograms>java PredefinedPackages
Languages: [Java, Python, C++]
Current Date: Mon May 25 10:30:00 IST 2026
File name: [Link]
Absolute path: C:\JavaPrograms\[Link]
Q5. AWT – Simple Window using Frame
import [Link].*;
import [Link].*;
public class SimpleFrame extends Frame {
SimpleFrame() {
setTitle("My First AWT Window");
setSize(400, 300);
setBackground(Color.LIGHT_GRAY);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new SimpleFrame();
[Link]("Window created successfully!");
}
}
C:\JavaPrograms>java SimpleFrame
Window created successfully!
(A 400x300 AWT window appears with title "My First AWT Window")
Q6. AWT – Button, Label, and TextField
import [Link].*;
import [Link].*;
public class AWTControls extends Frame {
AWTControls() {
setLayout(new FlowLayout());
setTitle("AWT Controls");
setSize(400, 200);
Label lbl = new Label("Enter Name:");
TextField tf = new TextField(20);
Button btn = new Button("Submit");
add(lbl); add(tf); add(btn);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); }
});
}
public static void main(String[] args) {
new AWTControls();
}
}
C:\JavaPrograms>java AWTControls
(AWT window displays Label, TextField and Submit button)
Q7. Button Click Event using ActionListener
import [Link].*;
import [Link].*;
public class ButtonClickEvent extends Frame implements ActionListener {
Label result;
ButtonClickEvent() {
setLayout(new FlowLayout());
setTitle("ActionListener Demo");
setSize(400, 200);
Button btn = new Button("Click Me");
result = new Label("Press the button");
[Link](this);
add(btn); add(result);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); }
});
}
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
[Link]("ActionEvent fired!");
}
public static void main(String[] args) {
new ButtonClickEvent();
}
}
C:\JavaPrograms>java ButtonClickEvent
(Before click): Label shows "Press the button"
(After click): Label shows "Button was clicked!"
Console output: ActionEvent fired!
Q8. Mouse Events using MouseListener
import [Link].*;
import [Link].*;
public class MouseEventDemo extends Frame implements MouseListener {
Label status;
MouseEventDemo() {
setTitle("Mouse Events");
setSize(400, 300);
setLayout(new FlowLayout());
status = new Label("Move or click the mouse");
add(status);
addMouseListener(this);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); }
});
}
public void mouseClicked(MouseEvent e) { [Link]("Mouse Clicked at
(" + [Link]() + "," + [Link]() + ")"); }
public void mousePressed(MouseEvent e) { [Link]("Mouse
Pressed"); }
public void mouseReleased(MouseEvent e) { [Link]("Mouse Released");
}
public void mouseEntered(MouseEvent e) { [Link]("Mouse
Entered"); }
public void mouseExited(MouseEvent e) { [Link]("Mouse Exited"); }
public static void main(String[] args) {
new MouseEventDemo();
}
}
C:\JavaPrograms>java MouseEventDemo
(When mouse enters window): Mouse Entered
(When mouse is clicked): Mouse Clicked at (200,150)
(When mouse exits window): Mouse Exited
Q9. Simple Applet – Display a Message
import [Link];
import [Link];
/*
<applet code="[Link]" width="400" height="200">
</applet>
*/
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Welcome to Java Applet!", 100, 100);
[Link]("Hello, World!", 100, 130);
}
}
C:\JavaPrograms>appletviewer [Link]
(AppletViewer window shows):
Welcome to Java Applet!
Hello, World!
Q10. Applet – Draw Shapes (Line, Rectangle, Circle)
import [Link];
import [Link].*;
/*
<applet code="[Link]" width="500" height="400">
</applet>
*/
public class DrawShapes extends Applet {
public void paint(Graphics g) {
// Draw Line
[Link]([Link]);
[Link](50, 50, 200, 50);
[Link]("Line", 110, 45);
// Draw Rectangle
[Link]([Link]);
[Link](50, 100, 150, 80);
[Link]("Rectangle", 95, 150);
// Draw Circle (oval with equal width & height)
[Link]([Link]);
[Link](50, 220, 100, 100);
[Link]("Circle", 85, 275);
// Filled Rectangle
[Link]([Link]);
[Link](220, 100, 150, 80);
[Link]([Link]);
[Link]("Filled Rect", 255, 150);
}
}
C:\JavaPrograms>appletviewer [Link]
(AppletViewer window shows):
- Red horizontal line labeled "Line"
- Blue outlined rectangle labeled "Rectangle"
- Green circle labeled "Circle"
- Orange filled rectangle labeled "Filled Rect"