Java OOP Practical Question Bank
Java OOP Practical Question Bank
(Eclipse Ready)
This document provides a comprehensive collection of Java OOP practical programs,
tailored to your syllabus for MSE 1, MSE 2, and ESE. Each topic includes 5-10 Eclipse-
ready code examples designed for hands-on practice and to help you score highly in
your exam.
MSE 1 Syllabus
1. BASIC JAVA
Program 1.1: Hello World Program
// Filename: [Link]
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!"); // Prints "Hello, World!" to
the console
}
}
if (number % 2 == 0) {
[Link](number + " is an even number.");
} else {
[Link](number + " is an odd number.");
}
}
}
[Link]("Hello, " + name + ". You are " + age + " years
old.");
void bark() {
[Link](name + " barks!");
}
}
// Filename: [Link]
public class TestDog {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create an object of Dog class
[Link] = "Buddy"; // Set object's state
[Link] = "Golden Retriever";
void displayCarInfo() {
[Link]("Make: " + make + ", Model: " + model + ", Year:
" + year);
}
}
// Filename: [Link]
public class TestCar {
public static void main(String[] args) {
Car car1 = new Car();
[Link] = "Toyota";
[Link] = "Camry";
[Link] = 2020;
[Link]();
// Filename: [Link]
public class TestCalculator {
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = [Link](10, 5);
int difference = [Link](10, 5);
void displayStudent() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
// Filename: [Link]
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student();
[Link](101, "Alice");
[Link]();
}
}
// Filename: [Link]
public class TestRectangle {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(10, 20);
Rectangle rect2 = new Rectangle(10, 20);
Rectangle rect3 = new Rectangle(15, 25);
3. CONSTRUCTOR
Program 3.1: Default Constructor
// Filename: [Link]
class DefaultConstructor {
int value;
// No-argument constructor
Bike() {
name = "Hero"; // Initialize default name
[Link]("Bike created with name: " + name);
}
// Parameterized constructor
Employee(int i, String n) {
id = i;
name = n;
[Link]("Employee created: ID=" + id + ", Name=" + name);
}
double volume() {
return width * height * depth;
}
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link]("ID: " + id + ", Name: " + name);
}
[Link]();
[Link]();
}
}
4. METHOD OVERLOADING
Program 4.1: Overloading by Number of Arguments
// Filename: [Link]
class Adder {
static int add(int a, int b) {
return a + b;
}
5. STATIC KEYWORD
Program 5.1: Static Variable
// Filename: [Link]
class Counter {
static int count = 0; // Static variable, shared by all objects
Counter() {
count++; // Increments each time an object is created
[Link]("Object created. Count: " + count);
}
void instanceMethod() {
[Link]("Instance method called.");
[Link]("Instance Var: " + instanceVar);
[Link]("Static Var from instance method: " + staticVar);
}
MSE 2 Syllabus
1. Inheritance
Program 6.1: Single Inheritance
// Filename: [Link]
class Animal {
void eat() {
[Link]("Animal is eating.");
}
}
// Filename: [Link]
class Dog extends Animal { // Dog inherits from Animal
void bark() {
[Link]("Dog is barking.");
}
}
// Filename: [Link]
public class TestSingleInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Method from Animal class
[Link](); // Method from Dog class
}
}
// Filename: [Link]
class Car extends Vehicle { // Car inherits from Vehicle
void changeGear() {
[Link]("Car is changing gear.");
}
}
// Filename: [Link]
class SportsCar extends Car { // SportsCar inherits from Car (multilevel)
void accelerate() {
[Link]("SportsCar is accelerating.");
}
}
// Filename: [Link]
public class TestMultilevelInheritance {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
[Link](); // From Vehicle
[Link](); // From Car
[Link](); // From SportsCar
}
}
// Filename: [Link]
class Circle extends Shape { // Circle inherits from Shape
void drawCircle() {
[Link]("Drawing a circle.");
}
}
// Filename: [Link]
class Rectangle extends Shape { // Rectangle also inherits from Shape
void drawRectangle() {
[Link]("Drawing a rectangle.");
}
}
// Filename: [Link]
public class TestHierarchicalInheritance {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
// Filename: [Link]
class Child extends Parent {
String message = "Hello from Child";
void display() {
[Link](message); // Refers to Child's message
[Link]([Link]); // Refers to Parent's message
}
}
// Filename: [Link]
public class TestSuperVariable {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
// Filename: [Link]
class DerivedClass extends BaseClass {
void show() {
[Link](); // Calls BaseClass's show() method
[Link]("DerivedClass's show() method.");
}
}
// Filename: [Link]
public class TestSuperMethod {
public static void main(String[] args) {
DerivedClass d = new DerivedClass();
[Link]();
}
}
// Filename: [Link]
class SuperConstructorChild extends SuperConstructorParent {
SuperConstructorChild() {
super(); // Calls Parent's no-arg constructor (implicitly called if
not present)
[Link]("Child class constructor called.");
}
SuperConstructorChild(String msg) {
super(msg); // Calls Parent's constructor with a String argument
[Link]("Child class constructor with message: " + msg);
}
}
// Filename: [Link]
public class TestSuperConstructor {
public static void main(String[] args) {
SuperConstructorChild c1 = new SuperConstructorChild();
SuperConstructorChild c2 = new SuperConstructorChild("Hello");
}
}
2. Method Overriding
Program 7.1: Basic Method Overriding
// Filename: [Link]
class VehicleOverride {
void run() {
[Link]("Vehicle is running.");
}
}
// Filename: [Link]
class Bike extends VehicleOverride {
@Override // Annotation to indicate method overriding
void run() {
[Link]("Bike is running safely at 60km/h.");
}
}
// Filename: [Link]
public class TestMethodOverriding {
public static void main(String[] args) {
Bike b = new Bike();
[Link](); // Calls the overridden run() method of Bike class
}
}
// Filename: [Link]
class Cat extends AnimalPoly {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}
// Filename: [Link]
class DogPoly extends AnimalPoly {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}
// Filename: [Link]
public class TestRuntimePoly {
public static void main(String[] args) {
AnimalPoly a; // Reference variable of parent class
// Filename: [Link]
class ChildReturn extends ParentReturn {
@Override
String getData() { // Covariant return type: String is a subclass of
Object
return "Some String Data";
}
}
// Filename: [Link]
public class TestCovariantReturn {
public static void main(String[] args) {
ChildReturn c = new ChildReturn();
[Link]([Link]());
}
}
// Filename: [Link]
class FinalMethodChild extends FinalMethodParent {
// void display() { // ERROR: Cannot override the final method from
FinalMethodParent
// [Link]("Trying to override final method.");
// }
public static void main(String[] args) {
[Link]("Final methods cannot be overridden. Uncomment
the display() method in FinalMethodChild to see the compile-time error.");
}
}
// Filename: [Link]
class StaticMethodChild extends StaticMethodParent {
static void show() { // This is method hiding, not overriding
[Link]("Child's static show() method.");
}
}
// Filename: [Link]
public class TestStaticMethodHiding {
public static void main(String[] args) {
[Link](); // Calls Parent's static method
[Link](); // Calls Child's static method
3. Abstract Class
Program 8.1: Simple Abstract Class and Method
// Filename: [Link]
abstract class VehicleAbstract {
abstract void run(); // Abstract method (no body)
// Filename: [Link]
class Honda extends VehicleAbstract {
@Override
void run() {
[Link]("Honda is running safely.");
}
}
// Filename: [Link]
public class TestAbstractClass {
public static void main(String[] args) {
Honda honda = new Honda();
[Link]();
[Link]();
// VehicleAbstract v = new VehicleAbstract(); // ERROR: Cannot
instantiate abstract class
}
}
void displayInfo() {
[Link]("This is a bank.");
}
}
// Filename: [Link]
class SBI extends Bank {
SBI() {
super("SBI Bank"); // Call abstract class constructor
}
@Override
int getRateOfInterest() {
return 7;
}
}
// Filename: [Link]
public class TestAbstractConstructor {
public static void main(String[] args) {
SBI sbi = new SBI();
[Link]("SBI Rate of Interest: " +
[Link]() + "%");
[Link]();
}
}
// Filename: [Link]
class FullTimeEmployee extends EmployeeAbstract {
double monthlySalary;
@Override
double calculateSalary() {
return monthlySalary;
}
}
// Filename: [Link]
public class TestEmployeeAbstract {
public static void main(String[] args) {
FullTimeEmployee ft = new FullTimeEmployee("David", 1001, 50000);
[Link]();
[Link]("Full-time Employee Salary: " +
[Link]());
}
}
// Template method
public final void play() {
initialize();
startPlay();
endPlay();
}
}
// Filename: [Link]
class Cricket extends Game {
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}
@Override
void endPlay() {
[Link]("Cricket Game Finished!");
}
}
// Filename: [Link]
public class TestGame {
public static void main(String[] args) {
Game game = new Cricket(); // Polymorphism
[Link]();
}
}
// Filename: [Link]
class ConcreteSubclass extends AbstractWithMain {
@Override
void abstractMethod() {
[Link]("Implementation of abstract method.");
}
4. Interface
Program 9.1: Simple Interface Implementation
// Filename: [Link]
interface Drawable {
void draw(); // Implicitly public and abstract
}
// Filename: [Link]
class CircleImpl implements Drawable {
@Override
public void draw() { // Must be public
[Link]("Drawing a circle.");
}
}
// Filename: [Link]
public class TestInterface {
public static void main(String[] args) {
Drawable d = new CircleImpl(); // Polymorphism
[Link]();
}
}
// Filename: [Link]
interface Showable {
void show();
}
// Filename: [Link]
class MyClass implements Printable, Showable {
@Override
public void print() {
[Link]("Printing...");
}
@Override
public void show() {
[Link]("Showing...");
}
}
// Filename: [Link]
public class TestMultipleInheritance {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
[Link]();
}
}
// Filename: [Link]
class MyClassWithDefault implements MyInterface {
@Override
public void abstractMethod() {
[Link]("Implementing abstract method.");
}
}
// Filename: [Link]
public class TestDefaultMethod {
public static void main(String[] args) {
MyClassWithDefault obj = new MyClassWithDefault();
[Link]();
[Link](); // Call default method
}
}
// Filename: [Link]
class SimpleCalculator implements CalculatorInterface {
@Override
public int add(int a, int b) {
return a + b;
}
}
// Filename: [Link]
public class TestStaticInterfaceMethod {
public static void main(String[] args) {
SimpleCalculator sc = new SimpleCalculator();
[Link]("Sum: " + [Link](5, 3));
// Call static method using interface name
[Link]("Product: " + [Link](5,
3));
}
}
// Filename: [Link]
interface B extends A { // Interface B inherits from A
void methodB();
}
// Filename: [Link]
class MyClassInterfaceInheritance implements B {
@Override
public void methodA() {
[Link]("Implementing methodA from interface A.");
}
@Override
public void methodB() {
[Link]("Implementing methodB from interface B.");
}
}
// Filename: [Link]
public class TestInterfaceInheritance {
public static void main(String[] args) {
MyClassInterfaceInheritance obj = new MyClassInterfaceInheritance();
[Link]();
[Link]();
}
}
5. Exception Handling
Program 10.1: Basic Try-Catch Block (ArithmeticException)
// Filename: [Link]
public class BasicException {
public static void main(String[] args) {
try {
int data = 100 / 0; // This will throw an ArithmeticException
[Link](data);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]("Rest of the code...");
}
}
// Filename: [Link]
public class CustomExceptionDemo {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote.");
} else {
[Link]("Welcome to vote.");
}
}
try {
validate(20);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}
}
}
void p() {
try {
n(); // Handling the exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}
6. Packages
Program 11.1: Creating and Using a Simple Package
Step 1: Create a directory structure. Create a folder my_package inside your
project’s src folder. Inside my_package , create [Link] .
Step 2: [Link] content.
// Filename: [Link] (inside my_package folder)
package my_package;
// Filename: [Link]
import [Link];
public class A {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30; // Default (package-private)
private int privateVar = 40; // Only accessible within class A
public class B {
public void testAccess() {
A objA = new A();
[Link]("From Class B (same package):");
[Link]("Public Var: " + [Link]);
[Link]("Protected Var: " + [Link]);
[Link]("Default Var: " + [Link]);
// [Link]("Private Var: " + [Link]); // ERROR:
private access
}
}
import pack1.A;
public class C {
public void testAccess() {
A objA = new A();
[Link]("From Class C (different package, not
subclass):");
[Link]("Public Var: " + [Link]);
// [Link]("Protected Var: " + [Link]); //
ERROR: protected access
// [Link]("Default Var: " + [Link]); //
ERROR: default access
}
}
import pack1.A;
ESE Syllabus
1. Multithreading
Program 12.1: Creating Thread by Extending Thread Class
// Filename: [Link]
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Filename: [Link]
public class TestThreadExtension {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1"); // Set thread name
MyThread t2 = new MyThread();
[Link]("Thread-2");
MyRunnable(String name) {
threadName = name;
[Link]("Creating " + threadName);
}
@Override
public void run() {
[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
}
// Filename: [Link]
public class TestRunnableImplementation {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable("Runnable-1");
Thread t1 = new Thread(runnable1); // Pass runnable object to Thread
constructor
[Link]();
// Filename: [Link]
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](5);
}
}
// Filename: [Link]
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](100);
}
}
// Filename: [Link]
public class TestSynchronization {
public static void main(String[] args) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
// Filename: [Link]
class ThreadA extends Thread {
SharedResource resource;
ThreadA(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}
// Filename: [Link]
class ThreadB extends Thread {
SharedResource resource;
ThreadB(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}
// Filename: [Link]
public class TestSynchronizedBlock {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
ThreadA tA = new ThreadA(sr);
ThreadB tB = new ThreadB(sr);
[Link]("Thread-A");
[Link]("Thread-B");
[Link]();
[Link]();
}
}
@Override
public void run() {
Thread myThread = new Thread(new MyRunnableState());
[Link]("State of myThread after creation: " +
[Link]());
[Link]();
try {
[Link](100); // thread1 sleeps, myThread runs
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after sleep: " +
[Link]());
try {
[Link](); // thread1 waits for myThread to die (WAITING
state)
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after join: " +
[Link]()); // TERMINATED
[Link]("State of thread1 at end of run: " +
[Link]().getState());
}
}
// Filename: [Link]
class MyRunnableState implements Runnable {
@Override
public void run() {
try {
[Link](1500); // Simulate some work
} catch (InterruptedException e) {
[Link]();
}
[Link]("MyRunnableState thread finished.");
}
}
class ProducerConsumer {
List<Integer> list = new ArrayList<>();
int capacity = 5;
// Filename: [Link]
public class TestProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
[Link]();
[Link]();
}
}
2. Applets
Program 13.1: Simple “Hello World” Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="300" height="200">
</applet>
*/
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello World from Applet!", 50, 100);
}
}
To run this:
1. Save the file as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.2: Applet with Parameters
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="300" height="200">
<param name="message" value="Welcome to Applets!">
</applet>
*/
public class ParamApplet extends Applet {
String message;
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.3: Applet Lifecycle Methods Demonstration
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class LifecycleApplet extends Applet {
String msg = "";
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Observe console output and applet window. Minimize/restore the applet
window to see stop() and start() calls. Close the AppletViewer to see
destroy() .
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class MouseEventApplet extends Applet implements MouseListener {
String msg = "";
int x = 0, y = 0;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint(); // Redraw the applet
}
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Interact with the applet using your mouse.
Program 13.5: Handling Keyboard Events in Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class KeyEventApplet extends Applet implements KeyListener {
String msg = "";
// KeyListener methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]([Link]());
repaint();
}
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Click on the applet window to give it focus, then press keys.
Prepared by Manus AI
2. Method Overriding
Program 7.1: Basic Method Overriding
// Filename: [Link]
class VehicleOverride {
void run() {
[Link]("Vehicle is running.");
}
}
// Filename: [Link]
class Bike extends VehicleOverride {
@Override // Annotation to indicate method overriding
void run() {
[Link]("Bike is running safely at 60km/h.");
}
}
// Filename: [Link]
public class TestMethodOverriding {
public static void main(String[] args) {
Bike b = new Bike();
[Link](); // Calls the overridden run() method of Bike class
}
}
// Filename: [Link]
class Cat extends AnimalPoly {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}
// Filename: [Link]
class DogPoly extends AnimalPoly {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}
// Filename: [Link]
public class TestRuntimePoly {
public static void main(String[] args) {
AnimalPoly a; // Reference variable of parent class
// Filename: [Link]
class ChildReturn extends ParentReturn {
@Override
String getData() { // Covariant return type: String is a subclass of
Object
return "Some String Data";
}
}
// Filename: [Link]
public class TestCovariantReturn {
public static void main(String[] args) {
ChildReturn c = new ChildReturn();
[Link]([Link]());
}
}
// Filename: [Link]
class FinalMethodChild extends FinalMethodParent {
// void display() { // ERROR: Cannot override the final method from
FinalMethodParent
// [Link]("Trying to override final method.");
// }
public static void main(String[] args) {
[Link]("Final methods cannot be overridden. Uncomment
the display() method in FinalMethodChild to see the compile-time error.");
}
}
// Filename: [Link]
class StaticMethodChild extends StaticMethodParent {
static void show() { // This is method hiding, not overriding
[Link]("Child's static show() method.");
}
}
// Filename: [Link]
public class TestStaticMethodHiding {
public static void main(String[] args) {
[Link](); // Calls Parent's static method
[Link](); // Calls Child's static method
3. Abstract Class
Program 8.1: Simple Abstract Class and Method
// Filename: [Link]
abstract class VehicleAbstract {
abstract void run(); // Abstract method (no body)
// Filename: [Link]
class Honda extends VehicleAbstract {
@Override
void run() {
[Link]("Honda is running safely.");
}
}
// Filename: [Link]
public class TestAbstractClass {
public static void main(String[] args) {
Honda honda = new Honda();
[Link]();
[Link]();
// VehicleAbstract v = new VehicleAbstract(); // ERROR: Cannot
instantiate abstract class
}
}
void displayInfo() {
[Link]("This is a bank.");
}
}
// Filename: [Link]
class SBI extends Bank {
SBI() {
super("SBI Bank"); // Call abstract class constructor
}
@Override
int getRateOfInterest() {
return 7;
}
}
// Filename: [Link]
public class TestAbstractConstructor {
public static void main(String[] args) {
SBI sbi = new SBI();
[Link]("SBI Rate of Interest: " +
[Link]() + "%");
[Link]();
}
}
// Filename: [Link]
class FullTimeEmployee extends EmployeeAbstract {
double monthlySalary;
@Override
double calculateSalary() {
return monthlySalary;
}
}
// Filename: [Link]
public class TestEmployeeAbstract {
public static void main(String[] args) {
FullTimeEmployee ft = new FullTimeEmployee("David", 1001, 50000);
[Link]();
[Link]("Full-time Employee Salary: " +
[Link]());
}
}
// Template method
public final void play() {
initialize();
startPlay();
endPlay();
}
}
// Filename: [Link]
class Cricket extends Game {
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}
@Override
void endPlay() {
[Link]("Cricket Game Finished!");
}
}
// Filename: [Link]
public class TestGame {
public static void main(String[] args) {
Game game = new Cricket(); // Polymorphism
[Link]();
}
}
// Filename: [Link]
class ConcreteSubclass extends AbstractWithMain {
@Override
void abstractMethod() {
[Link]("Implementation of abstract method.");
}
4. Interface
Program 9.1: Simple Interface Implementation
// Filename: [Link]
interface Drawable {
void draw(); // Implicitly public and abstract
}
// Filename: [Link]
class CircleImpl implements Drawable {
@Override
public void draw() { // Must be public
[Link]("Drawing a circle.");
}
}
// Filename: [Link]
public class TestInterface {
public static void main(String[] args) {
Drawable d = new CircleImpl(); // Polymorphism
[Link]();
}
}
// Filename: [Link]
interface Showable {
void show();
}
// Filename: [Link]
class MyClass implements Printable, Showable {
@Override
public void print() {
[Link]("Printing...");
}
@Override
public void show() {
[Link]("Showing...");
}
}
// Filename: [Link]
public class TestMultipleInheritance {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
[Link]();
}
}
// Filename: [Link]
class MyClassWithDefault implements MyInterface {
@Override
public void abstractMethod() {
[Link]("Implementing abstract method.");
}
}
// Filename: [Link]
public class TestDefaultMethod {
public static void main(String[] args) {
MyClassWithDefault obj = new MyClassWithDefault();
[Link]();
[Link](); // Call default method
}
}
// Filename: [Link]
class SimpleCalculator implements CalculatorInterface {
@Override
public int add(int a, int b) {
return a + b;
}
}
// Filename: [Link]
public class TestStaticInterfaceMethod {
public static void main(String[] args) {
SimpleCalculator sc = new SimpleCalculator();
[Link]("Sum: " + [Link](5, 3));
// Call static method using interface name
[Link]("Product: " + [Link](5,
3));
}
}
// Filename: [Link]
interface B extends A { // Interface B inherits from A
void methodB();
}
// Filename: [Link]
class MyClassInterfaceInheritance implements B {
@Override
public void methodA() {
[Link]("Implementing methodA from interface A.");
}
@Override
public void methodB() {
[Link]("Implementing methodB from interface B.");
}
}
// Filename: [Link]
public class TestInterfaceInheritance {
public static void main(String[] args) {
MyClassInterfaceInheritance obj = new MyClassInterfaceInheritance();
[Link]();
[Link]();
}
}
5. Exception Handling
Program 10.1: Basic Try-Catch Block (ArithmeticException)
// Filename: [Link]
public class BasicException {
public static void main(String[] args) {
try {
int data = 100 / 0; // This will throw an ArithmeticException
[Link](data);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]("Rest of the code...");
}
}
// Filename: [Link]
public class CustomExceptionDemo {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote.");
} else {
[Link]("Welcome to vote.");
}
}
try {
validate(20);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}
}
}
void p() {
try {
n(); // Handling the exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}
6. Packages
Program 11.1: Creating and Using a Simple Package
Step 1: Create a directory structure. Create a folder my_package inside your
project’s src folder. Inside my_package , create [Link] .
Step 2: [Link] content.
// Filename: [Link] (inside my_package folder)
package my_package;
// Filename: [Link]
import [Link];
public class A {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30; // Default (package-private)
private int privateVar = 40; // Only accessible within class A
public class B {
public void testAccess() {
A objA = new A();
[Link]("From Class B (same package):");
[Link]("Public Var: " + [Link]);
[Link]("Protected Var: " + [Link]);
[Link]("Default Var: " + [Link]);
// [Link]("Private Var: " + [Link]); // ERROR:
private access
}
}
import pack1.A;
public class C {
public void testAccess() {
A objA = new A();
[Link]("From Class C (different package, not
subclass):");
[Link]("Public Var: " + [Link]);
// [Link]("Protected Var: " + [Link]); //
ERROR: protected access
// [Link]("Default Var: " + [Link]); //
ERROR: default access
}
}
import pack1.A;
ESE Syllabus
1. Multithreading
Program 12.1: Creating Thread by Extending Thread Class
// Filename: [Link]
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Filename: [Link]
public class TestThreadExtension {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1"); // Set thread name
MyThread t2 = new MyThread();
[Link]("Thread-2");
MyRunnable(String name) {
threadName = name;
[Link]("Creating " + threadName);
}
@Override
public void run() {
[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
}
// Filename: [Link]
public class TestRunnableImplementation {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable("Runnable-1");
Thread t1 = new Thread(runnable1); // Pass runnable object to Thread
constructor
[Link]();
// Filename: [Link]
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](5);
}
}
// Filename: [Link]
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](100);
}
}
// Filename: [Link]
public class TestSynchronization {
public static void main(String[] args) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
// Filename: [Link]
class ThreadA extends Thread {
SharedResource resource;
ThreadA(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}
// Filename: [Link]
class ThreadB extends Thread {
SharedResource resource;
ThreadB(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}
// Filename: [Link]
public class TestSynchronizedBlock {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
ThreadA tA = new ThreadA(sr);
ThreadB tB = new ThreadB(sr);
[Link]("Thread-A");
[Link]("Thread-B");
[Link]();
[Link]();
}
}
@Override
public void run() {
Thread myThread = new Thread(new MyRunnableState());
[Link]("State of myThread after creation: " +
[Link]());
[Link]();
try {
[Link](100); // thread1 sleeps, myThread runs
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after sleep: " +
[Link]());
try {
[Link](); // thread1 waits for myThread to die (WAITING
state)
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after join: " +
[Link]()); // TERMINATED
[Link]("State of thread1 at end of run: " +
[Link]().getState());
}
}
// Filename: [Link]
class MyRunnableState implements Runnable {
@Override
public void run() {
try {
[Link](1500); // Simulate some work
} catch (InterruptedException e) {
[Link]();
}
[Link]("MyRunnableState thread finished.");
}
}
class ProducerConsumer {
List<Integer> list = new ArrayList<>();
int capacity = 5;
// Filename: [Link]
public class TestProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
[Link]();
[Link]();
}
}
2. Applets
Program 13.1: Simple “Hello World” Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="300" height="200">
</applet>
*/
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello World from Applet!", 50, 100);
}
}
To run this:
1. Save the file as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.2: Applet with Parameters
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="300" height="200">
<param name="message" value="Welcome to Applets!">
</applet>
*/
public class ParamApplet extends Applet {
String message;
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.3: Applet Lifecycle Methods Demonstration
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class LifecycleApplet extends Applet {
String msg = "";
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Observe console output and applet window. Minimize/restore the applet
window to see stop() and start() calls. Close the AppletViewer to see
destroy() .
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class MouseEventApplet extends Applet implements MouseListener {
String msg = "";
int x = 0, y = 0;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint(); // Redraw the applet
}
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Interact with the applet using your mouse.
Program 13.5: Handling Keyboard Events in Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class KeyEventApplet extends Applet implements KeyListener {
String msg = "";
// KeyListener methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]([Link]());
repaint();
}
To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Click on the applet window to give it focus, then press keys.
Prepared by Manus AI
1. Inheritance
Program 6.1: Single Inheritance
// Filename: [Link]
class Animal {
void eat() {
[Link]("Animal is eating.");
}
}
// Filename: [Link]
class Dog extends Animal { // Dog inherits from Animal
void bark() {
[Link]("Dog is barking.");
}
}
// Filename: [Link]
public class TestSingleInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Method from Animal class
[Link](); // Method from Dog class
}
}
// Filename: [Link]
class Car extends Vehicle { // Car inherits from Vehicle
void changeGear() {
[Link]("Car is changing gear.");
}
}
// Filename: [Link]
class SportsCar extends Car { // SportsCar inherits from Car (multilevel)
void accelerate() {
[Link]("SportsCar is accelerating.");
}
}
// Filename: [Link]
public class TestMultilevelInheritance {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
[Link](); // From Vehicle
[Link](); // From Car
[Link](); // From SportsCar
}
}
// Filename: [Link]
class Circle extends Shape { // Circle inherits from Shape
void drawCircle() {
[Link]("Drawing a circle.");
}
}
// Filename: [Link]
class Rectangle extends Shape { // Rectangle also inherits from Shape
void drawRectangle() {
[Link]("Drawing a rectangle.");
}
}
// Filename: [Link]
public class TestHierarchicalInheritance {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
// Filename: [Link]
class Child extends Parent {
String message = "Hello from Child";
void display() {
[Link](message); // Refers to Child\'s message
[Link]([Link]); // Refers to Parent\'s message
}
}
// Filename: [Link]
public class TestSuperVariable {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
// Filename: [Link]
class DerivedClass extends BaseClass {
void show() {
[Link](); // Calls BaseClass\'s show() method
[Link]("DerivedClass\'s show() method.");
}
}
// Filename: [Link]
public class TestSuperMethod {
public static void main(String[] args) {
DerivedClass d = new DerivedClass();
[Link]();
}
}
// Filename: [Link]
class SuperConstructorChild extends SuperConstructorParent {
SuperConstructorChild() {
super(); // Calls Parent\'s no-arg constructor (implicitly called if
not present)
[Link]("Child class constructor called.");
}
SuperConstructorChild(String msg) {
super(msg); // Calls Parent\'s constructor with a String argument
[Link]("Child class constructor with message: " + msg);
}
}
// Filename: [Link]
public class TestSuperConstructor {
public static void main(String[] args) {
SuperConstructorChild c1 = new SuperConstructorChild();
SuperConstructorChild c2 = new SuperConstructorChild("Hello");
}
}