Java Programming
Complete 5-Mark Answers
All 42 Questions Covered
Q1. Creating Your Own Package in Java with Multiple Classes
A package in Java is a namespace that organizes related classes and interfaces.
Steps:
● Use the package keyword at the top of the file.
● Save all classes in a folder matching the package name.
● Compile with javac and run using the full package path.
Example:
// File: mypack/[Link]
package mypack;
public class Hello {
public void greet() {
[Link]("Hello from Hello class!");
}
}
// File: mypack/[Link]
package mypack;
public class Bye {
public void sayBye() {
[Link]("Goodbye from Bye class!");
}
}
// File: [Link]
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
Bye b = new Bye();
[Link]();
}
}
Output:
Hello from Hello class!
Goodbye from Bye class!
Q2. Multiple Catch Blocks in Java
Java allows multiple catch blocks to handle different types of exceptions separately. Each catch block
handles a specific exception type.
Syntax:
try {
// risky code
} catch (ExceptionType1 e) {
// handle type 1
} catch (ExceptionType2 e) {
// handle type 2
}
Example:
public class MultiCatch {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 5; // ArrayIndexOutOfBoundsException
int x = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array error: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Math error: " + [Link]());
} catch (Exception e) {
[Link]("General error: " + [Link]());
}
}
}
Rules: More specific exceptions must come before general ones. Java 7+ allows multi-catch: catch
(Ex1 | Ex2 e).
Q3. Exception Handling with All Keywords
Keyword Purpose
try Wraps risky code
catch Handles the exception
finally Always executes (cleanup)
throw Manually throws an exception
throws Declares exceptions a method may throw
Example:
public class ExceptionDemo {
static void checkAge(int age) throws Exception {
if (age < 18)
throw new Exception("Age must be 18+");
[Link]("Access granted");
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Finally block always runs.");
}
}
}
Output:
Caught: Age must be 18+
Finally block always runs.
Q4. User-Defined Exception
A user-defined (custom) exception is created by extending the Exception class.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) { super(msg); }
}
public class CustomException {
static void validate(int age) throws InvalidAgeException {
if (age < 0 || age > 150)
throw new InvalidAgeException("Invalid age: " + age);
}
public static void main(String[] args) {
try {
validate(-5);
} catch (InvalidAgeException e) {
[Link]("Exception: " + [Link]());
}
}
}
Output: Exception: Invalid age: -5
Custom exceptions allow meaningful error messages tailored to the application's domain.
Q5. Thread Creation: Thread Class & Runnable Interface
Method 1 – Extending Thread class:
class MyThread extends Thread {
public void run() {
[Link]("Thread running: " + [Link]().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}
Method 2 – Implementing Runnable interface:
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread: " + [Link]().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}
Difference: Runnable is preferred because Java supports only single inheritance; using Runnable
allows the class to extend another class too.
Q6. Exception Handling with try, catch, finally
● finally block executes whether or not an exception occurs.
● Used for resource cleanup (closing files, DB connections).
public class TryCatchFinally {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
} finally {
[Link]("Closing resources...");
}
}
}
Q7. Inheritance, Abstract Class, Interface & String Handling
abstract class Animal {
String name;
Animal(String name) { [Link] = name; }
abstract void sound();
void display() { [Link]("Animal: " + [Link]()); }
}
interface Domestic {
void owner();
}
class Dog extends Animal implements Domestic {
Dog(String name) { super(name); }
public void sound() { [Link](name + " says: Woof!"); }
public void owner() { [Link]("Owner: John"); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Bruno");
[Link]();
[Link]();
[Link]();
String s = "Hello Java";
[Link]("Length: " + [Link]());
[Link]("Substring: " + [Link](6));
}
}
Output:
Animal: BRUNO
Bruno says: Woof!
Owner: John
Length: 10
Substring: Java
Q8. Packages in Java – Creation, Importing, Access Control
● Creation: Use package packageName; at the top of the file.
● Importing: Use import [Link]; or import packageName.*;
Access Control in Packages:
Modifier Same Class Same Package Subclass Other
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No
Built-in packages: [Link], [Link], [Link]. User-defined packages improve code organization,
reusability, and avoid naming conflicts.
Q9. Interface and Multiple Inheritance in Java
An interface is a blueprint with abstract methods (and constants). Java doesn't support multiple class
inheritance but allows multiple interfaces:
interface A { void showA(); }
interface B { void showB(); }
class C implements A, B {
public void showA() { [Link]("Interface A"); }
public void showB() { [Link]("Interface B"); }
}
public class Main {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}
This achieves multiple inheritance safely without the diamond problem.
Q10. Dynamic Method Dispatch & Runtime Polymorphism
Dynamic Method Dispatch is a mechanism where a call to an overridden method is resolved at runtime,
not compile-time. It is the basis of runtime polymorphism.
class Shape {
void draw() { [Link]("Drawing Shape"); }
}
class Circle extends Shape {
void draw() { [Link]("Drawing Circle"); }
}
class Square extends Shape {
void draw() { [Link]("Drawing Square"); }
}
public class Main {
public static void main(String[] args) {
Shape s;
s = new Circle(); [Link](); // Circle's draw()
s = new Square(); [Link](); // Square's draw()
}
}
Output:
Drawing Circle
Drawing Square
The parent reference s calls the child method — determined at runtime.
Q11. String and StringBuffer Classes with Important Methods
String – Immutable sequence of characters:
Method Description
length() Returns length
charAt(i) Character at index
substring(i,j) Extracts substring
toUpperCase() Converts to uppercase
equals(s) Compares content
indexOf(c) Finds index of char
StringBuffer – Mutable, thread-safe:
Method Description
append(s) Adds to end
insert(i,s) Inserts at position
delete(i,j) Deletes range
reverse() Reverses the string
replace(i,j,s) Replaces range
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link]();
[Link](sb); // dlroW olleH
Q12. Types of Inheritance with Multilevel Inheritance Program
Types of Inheritance:
● Single: A extends B
● Multilevel: A extends B, B extends C
● Hierarchical: A is extended by B and C
● Multiple: Via interfaces only
● Hybrid: Combination of above
Multilevel Inheritance Program:
class Grandparent {
void show() { [Link]("Grandparent"); }
}
class Parent extends Grandparent {
void display() { [Link]("Parent"); }
}
class Child extends Parent {
void print() { [Link]("Child"); }
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
[Link](); // from Grandparent
[Link](); // from Parent
[Link](); // own method
}
}
Q13. JDK, JRE, and JVM – Differences
Feature JVM JRE JDK
Full Form Java Virtual Machine Java Runtime Java Development Kit
Environment
Purpose Executes bytecode Provides runtime Develops Java
environment programs
Contains — JVM + libraries JRE + compiler + tools
Used by End users End users Developers
● JVM: Converts bytecode to machine code; platform-specific.
● JRE: JVM + standard libraries needed to run Java programs.
● JDK: JRE + javac compiler + debugger + other development tools.
Q14. Class Relationships: Association, Aggregation, Instantiation
● Association: A general relationship between two classes (uses-a). E.g., Teacher and Student.
● Aggregation (HAS-A): One class contains a reference to another; independent lifecycle.
● Instantiation: Creating an object of a class using new.
class Address {
String city;
Address(String city) { [Link] = city; }
}
class Employee { // Aggregation
String name;
Address addr;
Employee(String name, Address addr) {
[Link] = name; [Link] = addr;
}
void show() { [Link](name + " lives in " + [Link]); }
}
public class Main {
public static void main(String[] args) {
Address a = new Address("Kolkata"); // Instantiation
Employee e = new Employee("Raj", a); // Aggregation
[Link]();
}
}
Q15. Constructor Overloading and Method Overloading
Constructor Overloading: Multiple constructors with different parameters.
class Box {
int l, w, h;
Box() { l = w = h = 0; }
Box(int side) { l = w = h = side; }
Box(int l, int w, int h) { this.l=l; this.w=w; this.h=h; }
void show() { [Link](l + "x" + w + "x" + h); }
}
Method Overloading: Same method name, different parameters.
class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
Both are forms of compile-time (static) polymorphism.
Q16. Data Types, Operators, and Control Statements
Data Types:
● Primitive: int, float, double, char, boolean, byte, short, long
● Non-primitive: String, arrays, classes
Operators: Arithmetic (+,-,*,/,%), Relational (==,!=,<,>), Logical (&&,||,!), Bitwise, Assignment,
Ternary
Control Statements:
// if-else
if (x > 0) [Link]("Positive");
else [Link]("Non-positive");
// for loop
for (int i = 1; i <= 5; i++) [Link](i + " ");
// switch
switch (day) {
case 1: [Link]("Monday"); break;
default: [Link]("Other");
}
Q17. Class, Object, and Constructor in Detail
● Class: Template/blueprint defining attributes and methods.
● Object: Instance of a class created with new.
● Constructor: Special method called at object creation; same name as class, no return type.
class Student {
String name;
int age;
Student(String name, int age) { // Constructor
[Link] = name;
[Link] = age;
}
void display() {
[Link](name + " is " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Alice", 20); // Object creation
[Link]();
}
}
Q18. Thread Synchronization
Synchronization prevents multiple threads from accessing a shared resource simultaneously, avoiding
race conditions. Use the synchronized keyword:
class Counter {
int count = 0;
synchronized void increment() { count++; }
}
class MyThread extends Thread {
Counter c;
MyThread(Counter c) { this.c = c; }
public void run() {
for (int i = 0; i < 1000; i++) [Link]();
}
}
public class Main {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
MyThread t1 = new MyThread(c);
MyThread t2 = new MyThread(c);
[Link](); [Link]();
[Link](); [Link]();
[Link]("Count: " + [Link]); // Always 2000
}
}
Q19. Inter-Thread Communication
Inter-thread communication allows threads to cooperate using wait(), notify(), and notifyAll() methods
(from Object class).
class Shared {
int data; boolean ready = false;
synchronized void produce(int val) throws Exception {
while (ready) wait();
data = val; ready = true;
[Link]("Produced: " + data);
notify();
}
synchronized void consume() throws Exception {
while (!ready) wait();
[Link]("Consumed: " + data);
ready = false;
notify();
}
}
● wait() – releases lock and waits
● notify() – wakes one waiting thread
● notifyAll() – wakes all waiting threads
Q20. Difference Between throw and throws
Feature throw throws
Purpose Manually throws exception Declares possible exceptions
Location Inside method body In method signature
Usage throw new Exception() void m() throws Exception
Number Throws one exception Can declare multiple
void validate(int n) throws ArithmeticException {
if (n < 0) throw new ArithmeticException("Negative number");
}
Q21. Deadlock
Deadlock is a situation where two or more threads are blocked forever, each waiting for a resource held
by the other.
● Thread 1 holds Lock A, waits for Lock B
● Thread 2 holds Lock B, waits for Lock A
● Both wait forever = Deadlock
Prevention: Acquire locks in the same order, use tryLock(), or use timeout-based locking.
Q22. Thread Life Cycle
A thread goes through these states:
● New – Thread object created but start() not called.
● Runnable – start() called; waiting for CPU.
● Running – CPU is executing the thread.
● Blocked/Waiting – Waiting for I/O, lock, or sleep().
● Terminated (Dead) – run() method completed.
Flow: New → Runnable → Running → Blocked → Runnable → Terminated
Q23. What is a Thread in Java?
A thread is the smallest unit of execution within a program. Java supports multithreading — multiple
threads running concurrently within one program.
● Each thread has its own stack but shares heap memory.
● Created via Thread class or Runnable interface.
● Key methods: start(), run(), sleep(), join(), yield()
Thread t = new Thread(() -> [Link]("Hello from thread!"));
[Link]();
Q24. What is Exception Handling in Java?
Exception handling is a mechanism to handle runtime errors gracefully without crashing the program.
An exception is an abnormal event during execution.
● Checked exceptions: Compile-time (e.g., IOException, SQLException)
● Unchecked exceptions: Runtime (e.g., NullPointerException, ArithmeticException)
● Errors: Serious issues not meant to be caught (e.g., OutOfMemoryError)
Handled using try-catch-finally blocks and throw/throws keywords.
Q25. Importance of Reusability in OOP
Reusability means writing code once and using it multiple times, which is a key OOP principle achieved
through:
● Inheritance: Child class reuses parent class methods/fields.
● Interfaces: Multiple classes share the same method contract.
● Packages: Group reusable classes together.
● Polymorphism: Write generic code that works with multiple types.
Benefits: Saves development time, reduces bugs, easier maintenance, and promotes modular design.
Q26. Package Creation and Access Control
(Refer to Q8 — covers the same topic in full detail with access control table.)
Q27. Scanner Class for Input
Scanner (from [Link]) reads input from keyboard, files, or strings.
import [Link];
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter age: ");
int age = [Link]();
[Link]("Name: " + name + ", Age: " + age);
[Link]();
}
}
Key methods: next(), nextLine(), nextInt(), nextDouble(), nextBoolean()
Q28. Difference Between Abstract Class and Interface
Feature Abstract Class Interface
Methods Abstract + concrete Abstract (default/static in Java
8+)
Variables Any type public static final only
Inheritance extends (one only) implements (multiple)
Constructor Yes No
Access modifier Any public by default
Use case Partial implementation Full abstraction / multiple
inheritance
Q29. Difference Between String and StringBuffer
Feature String StringBuffer
Mutability Immutable Mutable
Thread Safety Yes (immutable) Yes (synchronized)
Performance Slower (new object each time) Faster for modifications
Memory More (creates new objects) Less
Methods length(), substring() append(), insert(), delete()
Use String for fixed text; StringBuffer when frequent modifications are needed.
Q30. What is an Interface in Java?
An interface is a fully abstract type in Java that defines a contract — what a class must do, not how.
● Declared with interface keyword.
● All methods are public abstract by default.
● All variables are public static final.
● A class uses implements to follow the contract.
interface Printable {
void print();
}
class Document implements Printable {
public void print() { [Link]("Printing document..."); }
}
Q31. Dynamic Method Dispatch
(Refer to Q10 — same topic with full program and output.)
Q32. The final Keyword in Java
Usage Meaning
final variable Value cannot be changed (constant)
final method Cannot be overridden in subclass
final class Cannot be subclassed/inherited
final class Constants {
final int MAX = 100; // constant
final void show() { [Link]("MAX = " + MAX); }
}
Q33. Superclass and Subclass in Java
● Superclass (Parent class): The class being inherited from.
● Subclass (Child class): The class that inherits from the parent.
class Animal { // Superclass
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal { // Subclass
void bark() { [Link]("Barking..."); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited
[Link](); // own
}
}
Q34. Access Specifiers in Java
Specifier Same Class Same Package Subclass Everywhere
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
● Use private for encapsulation.
● Use public for APIs.
● Use protected for inheritance scenarios.
Q35. Relationship Among Classes
● Association: General relationship; both classes can exist independently. E.g., Student uses
Library.
● Aggregation (HAS-A): Whole-part; parts can exist independently. E.g., Department has
Teachers.
● Composition (strong HAS-A): Parts cannot exist without the whole. E.g., House has Rooms.
● Using (Dependency): One class uses another temporarily (method parameter). E.g.,
print(Printer p).
(Refer to Q14 for code example.)
Q36. Garbage Collection
Garbage Collection (GC) is Java's automatic memory management that reclaims memory occupied by
unreferenced objects.
● JVM's GC runs automatically; no need to free memory manually (unlike C/C++).
● [Link]() can suggest GC but does not guarantee it.
● finalize() method is called before an object is collected (deprecated in Java 9+).
public class GCDemo {
protected void finalize() {
[Link]("Object collected by GC");
}
public static void main(String[] args) {
GCDemo obj = new GCDemo();
obj = null; // eligible for GC
[Link](); // suggest GC
}
}
Q37. Method Overloading vs Method Overriding
Feature Overloading Overriding
Where Same class Parent-child classes
Signature Different parameters Same signature
Return type Can differ Must be same (or covariant)
Binding Compile-time (static) Runtime (dynamic)
@Override Not needed Recommended
class Animal {
void sound() { [Link]("Some sound"); }
}
class Cat extends Animal {
void sound() { [Link]("Meow"); } // overriding
void sound(int times) { [Link]("Meow x" + times); } // overloading
}
Q38. Aggregation with Example
Aggregation is a HAS-A relationship where one class contains a reference to another, but both can
exist independently.
class Engine {
String type;
Engine(String type) { [Link] = type; }
}
class Car {
String model;
Engine engine; // Aggregation
Car(String model, Engine engine) {
[Link] = model;
[Link] = engine;
}
void show() {
[Link](model + " has " + [Link] + " engine");
}
}
public class Main {
public static void main(String[] args) {
Engine e = new Engine("V6");
Car c = new Car("Toyota", e);
[Link]();
}
}
Output: Toyota has V6 engine
Even if Car is deleted, Engine object still exists.
Q39. What is Inheritance in Java?
Inheritance is the mechanism where a child class acquires the properties and behaviors of a parent
class using the extends keyword.
Benefits: Code reusability, method overriding, polymorphism.
class Vehicle {
int speed = 80;
void move() { [Link]("Vehicle moving at " + speed); }
}
class Bike extends Vehicle {
void wheelie() { [Link]("Doing a wheelie!"); }
}
public class Main {
public static void main(String[] args) {
Bike b = new Bike();
[Link](); // inherited
[Link](); // own
}
}
Q40. The static Keyword in Java
Usage Meaning
static variable Shared among all objects
static method Called without creating object
static block Executes once when class loads
static class Nested static class
class MathUtils {
static int square(int n) { return n * n; }
static int PI_INT = 3;
}
public class Main {
public static void main(String[] args) {
[Link]([Link](5)); // 25
[Link](MathUtils.PI_INT); // 3
}
}
Q41. Encapsulation with Example
Encapsulation is wrapping data (variables) and methods together in a class, and restricting direct
access using private + getters/setters.
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
[Link](5000);
[Link]("Balance: " + [Link]());
// [Link] = -9999; // ERROR - private!
}
}
Benefits: Data hiding, controlled access, improved security and maintainability.
Q42. Class and Object in Java
● Class: A blueprint or template that defines data members (fields) and member functions
(methods).
● Object: A real-world instance of a class created using the new keyword.
class Car {
String brand;
int year;
Car(String brand, int year) {
[Link] = brand;
[Link] = year;
}
void info() {
[Link](brand + " (" + year + ")");
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("Toyota", 2022); // Object 1
Car c2 = new Car("Honda", 2023); // Object 2
[Link]();
[Link]();
}
}
Output:
Toyota (2022)
Honda (2023)