Complete
■ JAVA
OOP & Multithreading
Final Exam Preparation Guide
■ Topics Covered:
Polymorphism • Encapsulation • Inheritance • Abstraction • Interface • final / static / finally / this Keywords •
Access Modifiers • Input Taking • Pattern Printing • Exception Handling • Multithreading
Author
NAHIN UR ROSHID DURJOY
2025 Edition | Exam-Ready | Zero to Advanced
TABLE OF CONTENTS
PART 1: OBJECT-ORIENTED PROGRAMMING (OOP)
1. Polymorphism
2. Encapsulation
3. Inheritance
4. Abstraction
5. Interface
PART 2: IMPORTANT JAVA KEYWORDS
6. final Keyword
7. static Keyword
8. finally Keyword
9. this Keyword
10. Static Block & Instance Block
11. Access Modifiers
PART 3: INPUT, PATTERNS & EXCEPTIONS
12. Input Taking (Scanner, BufferedReader)
13. Pattern Printing
14. Exception Handling
PART 4: MULTITHREADING
15. Multithreading — Concepts & Thread Lifecycle
16. sleep() Method
17. Multithreading using Thread Class
18. Multithreading using Runnable Interface
19. join() Method
PART 5: QUESTION BANK
A. 100+ One-Mark Questions
B. 100+ True/False Questions
C. 50+ MCQ Questions
D. Brainstorming & Coding Questions
E. Output Tracing & Find the Error
APPENDICES
Final Revision Cheat Sheet
Common Mistakes Students Make
Last Night Revision Notes
Most Important for Exam
PART 1: OBJECT-ORIENTED PROGRAMMING (OOP)
CHAPTER 1: POLYMORPHISM
1.1 Definition
Polymorphism is one of the four pillars of Object-Oriented Programming. The word comes from Greek: poly
(many) + morph (forms). In Java, polymorphism means that a single method name or object reference
can behave differently depending on the context — i.e., the type of data it is handling or the class that is
being used at runtime.
1.2 Why Is It Needed?
• Allows you to write flexible, reusable code.
• Reduces the need to write multiple functions with different names for similar tasks.
• Enables one interface to control access to a general class of actions.
• Makes code more maintainable — change one place to affect all usages.
1.3 Real-Life Analogy
Think about a TV remote. The "Volume Up" button always increases volume whether you are watching
News, Movies, or Music. The same button (method) behaves consistently across different channels
(objects/classes). Similarly in Java, you call the same method name and Java internally decides which
version of the method to run.
1.4 Types of Polymorphism
Type Also Called Resolved At Mechanism
Compile-Time Polymorphism
Static Polymorphism Compile time Method Overloading
Runtime Polymorphism Dynamic Polymorphism Runtime Method Overriding + Upcasting
1.5 Method Overloading (Compile-Time)
Method Overloading means having multiple methods in the same class with the same name but
different parameters (different number, type, or order of parameters). The correct method is chosen by the
compiler based on the arguments you pass.
Syntax:
// Overloading: same name, different parameters
class Calculator {
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;
}
}
Complete Example with Output:
public class OverloadingDemo {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
[Link](add(5, 3)); // calls int version
[Link](add(2.5, 1.5)); // calls double version
[Link](add("Hello", " World")); // calls String version
}
}
Output:
8
4.0
Hello World
Line-by-Line Explanation:
1. Three add() methods exist — same name, different parameter types.
2. add(5, 3) → compiler sees two ints → calls int add(int,int) → returns 8.
3. add(2.5, 1.5) → compiler sees two doubles → calls double add(double,double) → returns 4.0.
4. add("Hello"," World") → compiler sees two Strings → calls String version → concatenates.
1.6 Method Overriding (Runtime Polymorphism)
Method Overriding occurs when a subclass provides its own implementation of a method that already
exists in the parent class. The signature (name + parameters) must be identical. The JVM decides at
runtime which version to run based on the actual object type.
Rules for Overriding:
• Method name and parameters must be the same.
• Return type must be same or a covariant (subtype).
• Access modifier cannot be more restrictive than parent.
• Cannot override static, final, or private methods.
• Use @Override annotation (best practice).
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks: Woof!");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows: Meow!");
}
}
public class OverridingDemo {
public static void main(String[] args) {
Animal a1 = new Dog(); // Upcasting
Animal a2 = new Cat(); // Upcasting
Animal a3 = new Animal();
[Link](); // Dog's sound()
[Link](); // Cat's sound()
[Link](); // Animal's sound()
}
}
Dog barks: Woof!
Cat meows: Meow!
Animal makes a sound
Dynamic Method Dispatch:
In the example above, a1 is declared as type Animal but refers to a Dog object. When [Link]() is called,
Java checks the actual object at runtime (Dog), not the reference type (Animal). This is called Dynamic
Method Dispatch — the cornerstone of runtime polymorphism.
1.7 Upcasting and Downcasting
Upcasting: Assigning a child class object to a parent class reference. This is implicit and safe.
Downcasting: Casting a parent reference back to a child type. Must be done explicitly and can throw
ClassCastException if incorrect.
class Shape {
void draw() { [Link]("Drawing shape"); }
}
class Circle extends Shape {
@Override
void draw() { [Link]("Drawing circle"); }
void extra() { [Link]("Circle-specific method"); }
}
public class CastDemo {
public static void main(String[] args) {
// Upcasting (implicit)
Shape s = new Circle();
[Link](); // Calls Circle's draw() - runtime polymorphism
// Downcasting (explicit)
Circle c = (Circle) s;
[Link](); // Now we can access Circle-specific method
}
}
Drawing circle
Circle-specific method
1.8 Common Mistakes
■■ Confusing overloading (same class, different params) with overriding (parent-child, same params).
■■ Trying to override a static method — that is method hiding, NOT overriding.
■■ Forgetting @Override annotation — the compiler won't warn you if you accidentally write a new method
instead of overriding.
■■ Trying to call child-specific methods through parent reference without downcasting.
1.9 Overloading vs Overriding — Comparison Table
Feature Overloading Overriding
Class Same class Parent-Child classes
Parameters Must differ Must be identical
Return type Can differ Must be same (or covariant)
Resolved at Compile time Runtime
Inheritance required No Yes
Access modifier Any Cannot be more restrictive
static/final/private Can overload Cannot override
Polymorphism type Compile-time Runtime
1.10 Exam Questions
Short Questions:
Q1. What is polymorphism in Java?
Ans: Polymorphism means "many forms." It allows one method or object reference to behave differently
depending on context. Java supports it via method overloading (compile-time) and method overriding
(runtime).
Q2. What is Dynamic Method Dispatch?
Ans: It is the mechanism by which Java determines which overridden method to call at runtime based on the
actual object type, not the reference type.
Q3. Can we overload the main() method?
Ans: Yes, we can overload main(). But the JVM only calls main(String[] args) as the entry point. Other
versions can be called manually.
Q4. What is upcasting?
Ans: Assigning a child class object to a parent class reference variable. It is implicit and enables runtime
polymorphism.
True/False:
1. Method overloading is resolved at runtime. — [False]
2. Method overriding requires a parent-child relationship. — [True]
3. A static method can be overridden in Java. — [False]
4. Upcasting can be done implicitly without a cast operator. — [True]
5. The @Override annotation is mandatory for method overriding. — [False]
CHAPTER 2: ENCAPSULATION
2.1 Definition
Encapsulation is the OOP principle of bundling data (fields/variables) and the methods that operate on
that data into a single unit (class), while restricting direct access to the data from outside the class. It is like
putting data in a capsule — protected from the outside world.
2.2 Why Is It Needed?
• Protects data from unauthorized access or modification.
• Provides control over what is read-only, write-only, or both.
• Makes code more maintainable — internal implementation can change without affecting outside code.
• Increases code reusability and reduces complexity.
2.3 Real-Life Analogy
Think of a bank account. You cannot directly set your balance to 1 million rupees by accessing the variable.
You must go through the deposit() or withdraw() methods, which apply business rules (e.g., no negative
balance). The balance is private; methods are the controlled interface.
2.4 How to Achieve Encapsulation
1. Declare all fields (variables) as private.
2. Provide public getter methods to read the values.
3. Provide public setter methods to modify the values (with validation if needed).
2.5 Code Example
public class BankAccount {
private String owner;
private double balance;
// Constructor
public BankAccount(String owner, double initialBalance) {
[Link] = owner;
if (initialBalance >= 0) {
[Link] = initialBalance;
} else {
[Link] = 0;
[Link]("Initial balance cannot be negative. Set to 0.");
}
}
// Getter for owner
public String getOwner() {
return owner;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter (controlled)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount);
} else {
[Link]("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient funds or invalid amount.");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 500.0);
[Link](200.0);
[Link](100.0);
[Link]("Balance: " + [Link]());
// [Link] = 9999; // ERROR! balance is private
}
}
Deposited: 200.0
Withdrawn: 100.0
Balance: 600.0
2.6 Read-Only and Write-Only Fields
Read-Only: Only provide a getter method, no setter.
Write-Only: Only provide a setter method, no getter (rare, but used e.g., for passwords).
class UserProfile {
private final String username; // read-only
private String password; // write-only (we won't provide getter)
public UserProfile(String username, String password) {
[Link] = username;
[Link] = password;
}
public String getUsername() { return username; } // read-only getter
public void setPassword(String newPass) { // write-only setter
if ([Link]() >= 8) {
[Link] = newPass;
[Link]("Password updated.");
} else {
[Link]("Password too short!");
}
}
}
2.7 Common Mistakes
■■ Making fields public defeats the purpose of encapsulation.
■■ Forgetting to validate in setters — a setter without validation just moves the problem.
■■ Returning mutable objects directly from getters — this breaks encapsulation! Return copies instead.
2.8 Exam Notes
■ Encapsulation = private fields + public getters/setters. This is also called a JavaBean or POJO (Plain Old Java
Object).
■ Encapsulation is about ACCESS CONTROL. It is different from Abstraction (which is about hiding
implementation details).
2.9 Exam Questions
Q1. What is encapsulation?
Ans: Encapsulation is bundling data and methods into a class while restricting direct access to fields using
private modifier and providing controlled access via public getters/setters.
Q2. What is a getter and setter?
Ans: A getter is a public method that returns a private field value. A setter is a public method that sets a
private field value, usually with validation.
1. Encapsulation is achieved by making fields public. — [False]
2. A class can have a getter without a setter for read-only fields. — [True]
3. Encapsulation and Abstraction are the same concept. — [False]
4. Private members of a class are accessible within the same class. — [True]
CHAPTER 3: INHERITANCE
3.1 Definition
Inheritance is the mechanism in Java where a child class (subclass) acquires the properties and
behaviors (fields and methods) of a parent class (superclass). It promotes code reuse — write once, use
in many places.
3.2 Why Is It Needed?
• Avoids code duplication by reusing existing class functionality.
• Establishes an IS-A relationship (Dog IS-A Animal).
• Enables runtime polymorphism through method overriding.
• Makes code easier to maintain and extend.
3.3 Real-Life Analogy
A child inherits traits from parents — eye color, height, surname. Similarly, a Dog class inherits eat(),
breathe(), sleep() from Animal class, and only adds bark() on top.
3.4 Syntax
class Parent {
// parent fields and methods
}
class Child extends Parent {
// child inherits everything non-private from parent
// child can add new fields/methods
// child can override parent methods
}
3.5 Types of Inheritance in Java
Type Supported? Description
Single ■ Yes One child, one parent: A → B
Multilevel ■ Yes Chain: A → B → C
Hierarchical ■ Yes Multiple children of one parent: A → B, A → C
Multiple (via class) ■ No Two parents, one child — NOT supported (Diamond Problem)
Multiple (via interface) ■ Yes Achieved using interfaces
Hybrid ■ Partial Mix of above — only through interfaces
3.6 Code Example — Single Inheritance
class Animal {
String name;
void eat() {
[Link](name + " is eating.");
}
void breathe() {
[Link](name + " is breathing.");
}
}
class Dog extends Animal {
void bark() {
[Link](name + " says: Woof!");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link] = "Buddy";
[Link](); // Inherited from Animal
[Link](); // Inherited from Animal
[Link](); // Dog's own method
}
}
Buddy is eating.
Buddy is breathing.
Buddy says: Woof!
3.7 Multilevel Inheritance
class Vehicle {
void start() { [Link]("Vehicle starting..."); }
}
class Car extends Vehicle {
void drive() { [Link]("Car driving..."); }
}
class ElectricCar extends Car {
void charge() { [Link]("Electric car charging..."); }
}
public class MultilevelDemo {
public static void main(String[] args) {
ElectricCar ec = new ElectricCar();
[Link](); // from Vehicle
[Link](); // from Car
[Link](); // own method
}
}
Vehicle starting...
Car driving...
Electric car charging...
3.8 The super Keyword
The super keyword refers to the immediate parent class. Uses:
• [Link]() — calls parent's method
• [Link] — accesses parent's field
• super() — calls parent's constructor (must be first line in child constructor)
class Person {
String name;
Person(String name) {
[Link] = name;
[Link]("Person constructor: " + name);
}
void greet() {
[Link]("Hello, I am " + name);
}
}
class Student extends Person {
int rollNo;
Student(String name, int rollNo) {
super(name); // calls Person's constructor
[Link] = rollNo;
[Link]("Student constructor: Roll " + rollNo);
}
@Override
void greet() {
[Link](); // calls Person's greet()
[Link]("My roll number is " + rollNo);
}
}
public class SuperDemo {
public static void main(String[] args) {
Student s = new Student("Alice", 101);
[Link]();
}
}
Person constructor: Alice
Student constructor: Roll 101
Hello, I am Alice
My roll number is 101
3.9 Why Java Does Not Support Multiple Class Inheritance —
Diamond Problem
If Java allowed class C extends A, B and both A and B had the same method display(), then [Link]() would
be ambiguous — which parent's method should be called? This is the Diamond Problem. Java avoids this
by disallowing multiple class inheritance. Instead, it uses interfaces which have default methods and force
the implementing class to resolve ambiguity explicitly.
3.10 Common Mistakes
■■ Thinking private members are inherited — they are NOT accessible in child class directly (though they exist in
memory). Use getter/setter.
■■ Forgetting to call super() when parent has a parameterized constructor and no default constructor.
■■ Confusing IS-A (inheritance) with HAS-A (composition).
3.11 Exam Questions
Q1. What is inheritance?
Ans: Inheritance is the OOP mechanism where a child class acquires the properties and behaviors of a
parent class using the extends keyword.
Q2. What is the Diamond Problem?
Ans: When a class inherits from two classes that both have the same method, there is ambiguity about which
method to use. Java avoids this by not allowing multiple class inheritance.
Q3. What does super() do?
Ans: super() calls the parent class constructor. It must be the first statement in the child constructor.
1. Java supports multiple inheritance through classes. — [False]
2. A child class inherits private members of the parent class. — [False]
3. super() must be the first statement in a constructor. — [True]
4. Java supports multilevel inheritance. — [True]
5. The extends keyword is used for inheritance. — [True]
CHAPTER 4: ABSTRACTION
4.1 Definition
Abstraction is the OOP principle of hiding complex implementation details and showing only the
essential features to the user. You define WHAT an object does, not HOW it does it.
4.2 Real-Life Analogy
When you drive a car, you use the steering wheel, accelerator, and brakes. You do not need to know the
internal combustion engine mechanics, fuel injection logic, or brake hydraulics. The car's interface (pedals,
wheel) abstracts away the complexity.
4.3 Ways to Achieve Abstraction in Java
Method Abstraction Level Keyword
Abstract Class Partial (0% to 100%) abstract
Interface 100% (before Java 8) interface
4.4 Abstract Class
An abstract class is a class declared with the abstract keyword. It can have both abstract methods (without
body) and concrete methods (with body). It CANNOT be instantiated directly.
abstract class Shape {
String color;
// Constructor (yes, abstract class CAN have constructor)
Shape(String color) {
[Link] = color;
}
// Abstract method - no body, subclass MUST implement it
abstract double area();
// Concrete method - has body
void display() {
[Link]("Shape color: " + color);
}
}
class Circle extends Shape {
double radius;
Circle(String color, double radius) {
super(color);
[Link] = radius;
}
@Override
double area() {
return [Link] * radius * radius;
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(String color, double length, double width) {
super(color);
[Link] = length;
[Link] = width;
}
@Override
double area() {
return length * width;
}
}
public class AbstractDemo {
public static void main(String[] args) {
Shape s1 = new Circle("Red", 5.0);
Shape s2 = new Rectangle("Blue", 4.0, 6.0);
[Link]();
[Link]("Circle area: %.2f%n", [Link]());
[Link]();
[Link]("Rectangle area: %.2f%n", [Link]());
}
}
Shape color: Red
Circle area: 78.54
Shape color: Blue
Rectangle area: 24.00
4.5 Abstract Class Rules
• Declared with abstract keyword.
• Cannot be instantiated (cannot use new directly).
• Can have constructors, fields, concrete methods, and abstract methods.
• If a class has even ONE abstract method, it must be declared abstract.
• Subclass MUST implement all abstract methods, OR subclass itself must be abstract.
4.6 Abstract Class vs Interface
Feature Abstract Class Interface
Keyword abstract class interface
Instantiation Cannot instantiate Cannot instantiate
Method types Abstract + Concrete Abstract (+ default, static in Java 8+)
Fields Any type Only public static final (constants)
Constructor Yes No
Multiple inheritance No (single extends) Yes (implements multiple)
Access modifiers Any public by default for abstract methods
Use when Sharing common code between relatedDefining
classes a contract for unrelated classes
4.7 Common Mistakes
■■ Trying to instantiate an abstract class — this causes a compile error.
■■ Not implementing all abstract methods in a concrete subclass.
■■ Thinking abstract class and interface are interchangeable — they have different use cases.
4.8 Exam Questions
Q1. What is an abstract class?
Ans: A class declared with the abstract keyword that cannot be instantiated and may contain abstract
(unimplemented) methods that subclasses must implement.
Q2. Can an abstract class have a constructor?
Ans: Yes. Even though you cannot create an object of an abstract class directly, constructors are used when
a subclass calls super().
Q3. What happens if a subclass does not implement all abstract methods?
Ans: The subclass itself must be declared abstract, otherwise it is a compile-time error.
1. An abstract class can be instantiated directly. — [False]
2. An abstract class can have both abstract and concrete methods. — [True]
3. A subclass of an abstract class must implement all abstract methods. — [True]
4. Interfaces can have constructors. — [False]
CHAPTER 5: INTERFACE
5.1 Definition
An interface in Java is a blueprint/contract that a class agrees to follow. It defines WHAT a class must do,
but not HOW. All methods in an interface are by default public and abstract (before Java 8). A class uses the
implements keyword to follow an interface's contract.
5.2 Real-Life Analogy
Think of a power socket (interface). Any device (class) that wants to use electricity must have a plug that fits
the socket. The socket defines the contract (2-pin, 3-pin). Any device following that contract can plug in,
regardless of whether it's a phone, laptop, or fan.
5.3 Syntax
interface InterfaceName {
// public static final variables (constants)
int MAX_SPEED = 120; // implicitly public static final
// public abstract methods
void method1(); // implicitly public abstract
int method2(int x);
// Java 8+: default method (has body)
default void defaultMethod() {
[Link]("Default implementation");
}
// Java 8+: static method
static void staticMethod() {
[Link]("Static in interface");
}
}
class MyClass implements InterfaceName {
public void method1() { /* implementation */ }
public int method2(int x) { return x * 2; }
}
5.4 Complete Interface Example
interface Printable {
void print();
}
interface Showable {
void show();
}
// A class implementing multiple interfaces
class Document implements Printable, Showable {
String content;
Document(String content) {
[Link] = content;
}
@Override
public void print() {
[Link]("Printing: " + content);
}
@Override
public void show() {
[Link]("Showing: " + content);
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Document doc = new Document("Java Guide");
[Link]();
[Link]();
// Using interface reference (polymorphism)
Printable p = new Document("Report");
[Link]();
}
}
Printing: Java Guide
Showing: Java Guide
Printing: Report
5.5 Multiple Inheritance via Interface
Java does not allow multiple class inheritance, but a class CAN implement multiple interfaces. If two
interfaces have a default method with the same name, the implementing class MUST override it to resolve
the conflict.
interface A {
default void greet() {
[Link]("Hello from A");
}
}
interface B {
default void greet() {
[Link]("Hello from B");
}
}
class C implements A, B {
@Override
public void greet() {
[Link](); // explicitly choose A's version
[Link]("Hello from C (overriding conflict)");
}
}
public class MultipleInterfaceDemo {
public static void main(String[] args) {
C obj = new C();
[Link]();
}
}
Hello from A
Hello from C (overriding conflict)
5.6 Interface Key Points
• Variables in interface are implicitly public, static, and final.
• Methods are implicitly public and abstract (unless default/static in Java 8+).
• A class can implement multiple interfaces.
• An interface can extend multiple interfaces.
• Interface cannot be instantiated but can hold reference of implementing class.
• Java 8 added default and static methods to interfaces.
• Java 9 added private methods to interfaces.
5.7 Common Mistakes
■■ Trying to declare instance variables in an interface — they must be constants (public static final).
■■ Not providing public modifier in implementation — interface methods must be public when implemented.
■■ Confusing implements (for interface) with extends (for class/interface).
5.8 Exam Questions
Q1. What is the difference between an interface and abstract class?
Ans: An interface is a pure contract with no implementation (before Java 8), supports multiple inheritance,
and all fields are constants. An abstract class can have constructors, instance fields, concrete methods, and
only supports single inheritance.
Q2. Can an interface extend another interface?
Ans: Yes. An interface can extend one or more interfaces using the extends keyword.
Q3. What are default methods in interfaces?
Ans: Introduced in Java 8, default methods are concrete methods in interfaces that provide a default
implementation. Implementing classes can override them.
1. A class can implement multiple interfaces in Java. — [True]
2. Interface variables can be changed after initialization. — [False]
3. Interface methods are public and abstract by default. — [True]
4. An interface can have a constructor. — [False]
5. Java 8 introduced default methods in interfaces. — [True]
PART 2: IMPORTANT JAVA KEYWORDS
CHAPTER 6: THE final KEYWORD
6.1 Definition
The final keyword in Java means "this cannot be changed." It can be applied to variables, methods, and
classes, with different effects in each case.
6.2 Uses of final
Applied To Effect
Variable Becomes a constant — value cannot be changed after assignment
Method Cannot be overridden by subclasses
Class Cannot be inherited (cannot be subclassed)
6.3 final Variable
public class FinalVariableDemo {
public static void main(String[] args) {
final int MAX = 100;
[Link]("Max: " + MAX);
// MAX = 200; // ERROR! Cannot change a final variable
final double PI = 3.14159;
[Link]("PI: " + PI);
}
}
Max: 100
PI: 3.14159
A final instance variable must be initialized either at declaration or in the constructor:
class Circle {
final double PI;
double radius;
Circle(double r) {
[Link] = 3.14159; // OK to initialize in constructor
[Link] = r;
}
}
6.4 final Method
class Parent {
final void display() {
[Link]("Parent's final method");
}
}
class Child extends Parent {
// void display() { } // ERROR! Cannot override final method
}
6.5 final Class
final class ImmutableClass {
int x = 10;
void show() { [Link]("x = " + x); }
}
// class Extended extends ImmutableClass { } // ERROR! Cannot extend final class
■ The String class in Java is declared final — that's why String cannot be subclassed.
6.6 final vs finally vs finalize
Keyword Type Purpose
final Modifier keyword Makes variable constant, method non-overridable, class non-inheritable
finally Exception block Code that always executes after try-catch, for cleanup
finalize() Method (deprecated) Called by GC before object is destroyed (Java 9+ deprecated)
■■ These three are VERY commonly tested in exams. Know them by heart!
6.7 Exam Questions
Q1. What are the three uses of the final keyword?
Ans: (1) final variable = constant, (2) final method = cannot be overridden, (3) final class = cannot be
extended.
Q2. What is the difference between final, finally, and finalize?
Ans: final is a modifier for constants/methods/classes; finally is a block in exception handling that always
executes; finalize() is a method called by garbage collector before destroying object.
1. A final variable can be changed once after initialization. — [False]
2. A final class can be instantiated. — [True]
3. String class in Java is a final class. — [True]
4. A final method can be overridden in a subclass. — [False]
CHAPTER 7: THE static KEYWORD
7.1 Definition
The static keyword means that a member (variable, method, block, or nested class) belongs to the class
itself, not to any individual object. Static members are shared across all instances.
7.2 Real-Life Analogy
Imagine a company. The company name is the same for all employees (static variable). But each employee
has their own employee ID (instance variable). The company name does not change per employee.
7.3 Static Variable
class Employee {
static String companyName = "TechCorp"; // Shared by all
String name;
int id;
Employee(String name, int id) {
[Link] = name;
[Link] = id;
}
void display() {
[Link](name + " | ID: " + id + " | Company: " + companyName);
}
}
public class StaticVariableDemo {
public static void main(String[] args) {
Employee e1 = new Employee("Alice", 101);
Employee e2 = new Employee("Bob", 102);
[Link]();
[Link]();
// Change company name - affects ALL employees
[Link] = "NewTechCorp";
[Link]();
[Link]();
}
}
Alice | ID: 101 | Company: TechCorp
Bob | ID: 102 | Company: TechCorp
Alice | ID: 101 | Company: NewTechCorp
Bob | ID: 102 | Company: NewTechCorp
7.4 Static Method
class MathUtils {
static int square(int n) {
return n * n;
}
static double circleArea(double r) {
return 3.14159 * r * r;
}
}
public class StaticMethodDemo {
public static void main(String[] args) {
// No object needed - called on class directly
[Link]("Square of 5: " + [Link](5));
[Link]("Area of circle (r=4): %.2f%n", [Link](4));
}
}
Square of 5: 25
Area of circle (r=4): 50.27
7.5 Rules for Static Methods
• Can be called using [Link]() without creating an object.
• Can only access static variables and call other static methods directly.
• CANNOT use this or super keywords (no object context).
• Cannot access instance (non-static) variables directly.
• main() is static because JVM needs to call it without creating an object.
7.6 Static Counter Example (Counting Objects)
class Counter {
static int count = 0; // Shared across all objects
Counter() {
count++;
[Link]("Object " + count + " created.");
}
static void showCount() {
[Link]("Total objects: " + count);
}
}
public class CounterDemo {
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
[Link]();
}
}
Object 1 created.
Object 2 created.
Object 3 created.
Total objects: 3
7.7 Common Mistakes
■■ Trying to use this inside a static method — this doesn't exist in static context!
■■ Accessing instance variables from a static method without an object reference.
■■ Assuming static variables are reset for each object — they are NOT, they belong to the class.
7.8 Exam Questions
Q1. Why is main() method static?
Ans: Because JVM needs to call main() before any object is created. Static methods can be called without an
object.
Q2. Can static methods access instance variables?
Ans: No, not directly. They can access instance variables only through an object reference.
1. Static variables are shared across all instances of a class. — [True]
2. Static methods can use the this keyword. — [False]
3. A static method can call a non-static method directly. — [False]
4. Static members are loaded when the class is first loaded into memory. — [True]
CHAPTER 8: THE finally KEYWORD
8.1 Definition
The finally block is a part of Java's exception handling mechanism. It is a block of code that always
executes after the try-catch block, regardless of whether an exception occurred or not. It is used for cleanup
operations — closing files, releasing resources, closing database connections, etc.
8.2 Syntax
try {
// code that might throw exception
} catch (ExceptionType e) {
// handle exception
} finally {
// ALWAYS runs - cleanup code here
}
8.3 Code Example
public class FinallyDemo {
public static void main(String[] args) {
[Link]("--- Case 1: No Exception ---");
try {
[Link]("Try block: 10 / 2 = " + (10/2));
} catch (ArithmeticException e) {
[Link]("Catch: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
[Link]("
--- Case 2: Exception Occurs ---");
try {
[Link]("Try block: 10 / 0 = " + (10/0));
} catch (ArithmeticException e) {
[Link]("Catch: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
}
}
--- Case 1: No Exception ---
Try block: 10 / 2 = 5
Finally block executed.
--- Case 2: Exception Occurs ---
Catch: / by zero
Finally block executed.
8.4 When finally Does NOT Execute
• When [Link]() is called inside try or catch.
• When the JVM crashes.
• When the thread executing try-catch is forcefully killed.
public class FinallyNoRunDemo {
public static void main(String[] args) {
try {
[Link]("In try block");
[Link](0); // JVM exits here
} finally {
[Link]("This will NOT print!");
}
}
}
In try block
8.5 Exam Notes
■ finally is used for resource cleanup. In modern Java (7+), try-with-resources (AutoCloseable) is preferred over
finally for closing resources.
■ A try block can exist with only finally and no catch: try { } finally { } is valid.
8.6 Exam Questions
Q1. Will finally block execute if return statement is in try?
Ans: Yes! finally executes even if there is a return statement in the try block. The return value is computed,
then finally runs, then the method returns.
Q2. What is the main purpose of the finally block?
Ans: To perform cleanup operations like closing files, database connections, or releasing resources, ensuring
they happen regardless of exceptions.
1. finally block always executes after try-catch. — [True]
2. finally block runs even when [Link]() is called. — [False]
3. A try block can have multiple finally blocks. — [False]
4. finally block is mandatory in exception handling. — [False]
CHAPTER 9: THE this KEYWORD
9.1 Definition
The this keyword in Java is a reference to the current object — the object on which the method or
constructor is being called. It is available in instance methods and constructors but NOT in static methods.
9.2 Uses of this
Use Description
[Link] Refers to current class instance variable (resolves variable shadowing)
[Link]() Calls another method of current class
this() Calls another constructor of same class (constructor chaining)
return this Returns current object (useful in builder pattern/method chaining)
pass this Passes current object as parameter to another method
9.3 Resolving Variable Shadowing
class Student {
String name;
int age;
// Without this: parameter name shadows instance variable
Student(String name, int age) {
[Link] = name; // [Link] = instance variable, name = parameter
[Link] = age;
}
void display() {
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}
public class ThisDemo {
public static void main(String[] args) {
Student s = new Student("Alice", 20);
[Link]();
}
}
Name: Alice, Age: 20
9.4 Constructor Chaining with this()
class Box {
int length, width, height;
Box() {
this(1, 1, 1); // calls Box(int, int, int)
[Link]("Default box created.");
}
Box(int l, int w, int h) {
[Link] = l;
[Link] = w;
[Link] = h;
[Link]("Box: " + l + "x" + w + "x" + h);
}
}
public class ConstructorChainingDemo {
public static void main(String[] args) {
Box b1 = new Box(); // calls default -> parameterized
Box b2 = new Box(3, 4, 5); // calls parameterized directly
}
}
Box: 1x1x1
Default box created.
Box: 3x4x5
9.5 Common Mistakes
■■ Using this() after another statement in a constructor — this() MUST be the first statement.
■■ Using this inside a static method — static methods have no current object.
■■ Confusing this() (constructor call) with this (object reference).
9.6 Exam Questions
Q1. What does this keyword refer to?
Ans: this refers to the current instance of the class — the object on which the method or constructor is being
invoked.
Q2. Can we use this in a static method?
Ans: No. Static methods belong to the class and are not tied to any object, so there is no "current object"
reference.
Q3. What is constructor chaining?
Ans: Calling one constructor from another using this(). It helps avoid code duplication. this() must be the first
statement.
1. this keyword can be used inside a static method. — [False]
2. this() must be the first statement in a constructor. — [True]
3. this refers to the parent class object. — [False]
4. this can be used to pass the current object as a method argument. — [True]
CHAPTER 10: STATIC BLOCK & INSTANCE (INIT)
BLOCK
10.1 Static Block
A static block is a block of code inside a class marked with the static keyword. It runs once when the class
is first loaded into memory — before any objects are created or any static method is called. Used for static
variable initialization or one-time setup.
class StaticBlockDemo {
static int x;
int y;
static {
x = 50;
[Link]("Static block executed. x = " + x);
}
{
y = 100;
[Link]("Instance block executed. y = " + y);
}
StaticBlockDemo() {
[Link]("Constructor executed.");
}
public static void main(String[] args) {
[Link]("main() started.");
StaticBlockDemo obj1 = new StaticBlockDemo();
[Link]("---");
StaticBlockDemo obj2 = new StaticBlockDemo();
}
}
Static block executed. x = 50
main() started.
Instance block executed. y = 100
Constructor executed.
---
Instance block executed. y = 100
Constructor executed.
10.2 Key Observations
• Static block runs ONCE when class is loaded (even before main).
• Instance block runs EVERY TIME an object is created, BEFORE the constructor.
• Order: Static block → main() → Instance block → Constructor (for each object).
• Multiple static/instance blocks are allowed; they execute top to bottom.
10.3 Instance (Initializer) Block
An instance block (also called instance initializer block) is a block of code inside a class but outside any
method. It runs before the constructor every time an object is created.
10.4 Comparison Table
Feature Static Block Instance Block
Keyword static { } { } (no keyword)
Runs when Class is first loaded Every time object is created
Frequency Once per class load Once per object creation
Access Only static members Both static and instance members
Use case Static variable init, one-time setup Shared init code for all constructors
10.5 Exam Questions
Q1. When does a static block execute?
Ans: A static block executes once when the class is first loaded into JVM memory, before any object creation
or static method call.
Q2. What is the execution order of static block, instance block, and constructor?
Ans: Static block → (object creation) Instance block → Constructor.
1. Static block executes every time an object is created. — [False]
2. Instance block executes before the constructor. — [True]
3. Static block can access instance variables directly. — [False]
4. Multiple static blocks are allowed in a class. — [True]
CHAPTER 11: ACCESS MODIFIERS
11.1 Definition
Access modifiers in Java control the visibility and accessibility of classes, fields, methods, and
constructors. They define who can access what.
11.2 The Four Access Modifiers
Modifier Same Class Same Package Subclass (diff package) Other Class (diff package)
private ■ Yes ■ No ■ No ■ No
default (no keyword) ■ Yes ■ Yes ■ No ■ No
protected ■ Yes ■ Yes ■ Yes ■ No
public ■ Yes ■ Yes ■ Yes ■ Yes
11.3 private
Most restrictive. Only accessible within the same class. Used for encapsulation.
class Secret {
private int pin = 1234;
private void show() {
[Link]("Pin: " + pin); // OK - same class
}
public void access() {
show(); // Can call private method from same class
}
}
11.4 default (Package-Private)
No keyword written. Accessible within the same package only.
class PackageClass {
int defaultVar = 10; // package-private
void defaultMethod() {
[Link]("Default access: " + defaultVar);
}
}
11.5 protected
Accessible within the same package AND by subclasses in any package.
class Parent {
protected String family = "Smith";
protected void introduce() {
[Link]("I am a " + family);
}
}
class Child extends Parent {
void show() {
introduce(); // Can access protected from parent
[Link]("Family: " + family);
}
}
11.6 public
Least restrictive. Accessible from anywhere.
public class PublicClass {
public int value = 42;
public void display() {
[Link]("Value: " + value);
}
}
11.7 Common Mistakes
■■ Using private in an interface method — interface methods are public by default and must be public when
implemented.
■■ Forgetting that default access is NOT the same as public.
■■ Confusing protected with public — protected does NOT allow access from different packages unless through
inheritance.
11.8 Exam Questions
Q1. Which access modifier provides the widest access?
Ans: public — accessible from anywhere in the program.
Q2. What is default access modifier?
Ans: When no access modifier is specified, the member is package-private — accessible only within the
same package.
Q3. Can protected members be accessed from a different package?
Ans: Yes, but only through inheritance (subclasses). Not accessible directly from unrelated classes in a
different package.
1. private members are accessible in subclasses. — [False]
2. protected allows access from any class in any package. — [False]
3. The default access modifier allows access within the same package. — [True]
4. public is the most restrictive access modifier. — [False]
PART 3: INPUT, PATTERNS & EXCEPTION HANDLING
CHAPTER 12: INPUT TAKING IN JAVA
12.1 Using Scanner Class
Scanner is the most commonly used class for taking input in Java. It is in the [Link] package.
import [Link];
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int num = [Link]();
[Link]("Enter a double: ");
double d = [Link]();
[Link](); // consume leftover newline after nextDouble()
[Link]("Enter a word: ");
String word = [Link]();
[Link](); // consume leftover newline after next()
[Link]("Enter a full sentence: ");
String sentence = [Link]();
[Link]("Int: " + num);
[Link]("Double: " + d);
[Link]("Word: " + word);
[Link]("Sentence: " + sentence);
[Link]();
}
}
12.2 Scanner Methods Quick Reference
Method Input Type Example
nextInt() Integer (int) int x = [Link]();
nextLong() Long integer long n = [Link]();
nextDouble() Decimal number double d = [Link]();
nextFloat() Float float f = [Link]();
next() Single word (stops at space)String w = [Link]();
nextLine() Full line including spaces String line = [Link]();
nextBoolean() true/false boolean b = [Link]();
nextChar()* No direct method char c = [Link]().charAt(0);
12.3 The Classic nextInt() then nextLine() Bug
■■ This is one of the MOST common bugs in Java input. After nextInt() or nextDouble(), a newline character stays
in the buffer. The next nextLine() reads that empty newline instead of your actual input!
// WRONG - Bug demonstration
Scanner sc = new Scanner([Link]);
int age = [Link](); // reads integer, leaves \n in buffer
String name = [Link](); // reads the leftover \n - gets empty string!
// CORRECT - Fix with extra nextLine()
int age = [Link]();
[Link](); // consume the leftover newline
String name = [Link](); // now reads actual input
12.4 BufferedReader for Faster Input
For competitive programming or large inputs, BufferedReader is faster than Scanner.
import [Link];
import [Link];
import [Link];
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name: ");
String name = [Link](); // reads entire line
[Link]("Enter age: ");
int age = [Link]([Link]()); // parse string to int
[Link]("Name: " + name + ", Age: " + age);
}
}
12.5 Command-Line Arguments
public class CommandLineDemo {
public static void main(String[] args) {
// Run: java CommandLineDemo Hello World 42
[Link]("Number of args: " + [Link]);
for (int i = 0; i < [Link]; i++) {
[Link]("args[" + i + "] = " + args[i]);
}
}
}
Number of args: 3
args[0] = Hello
args[1] = World
args[2] = 42
12.6 Exam Questions
Q1. What is the difference between next() and nextLine()?
Ans: next() reads a single token (stops at whitespace). nextLine() reads an entire line including spaces until
newline character.
Q2. Why is nextLine() sometimes skipped after nextInt()?
Ans: Because nextInt() leaves a newline character in the buffer. nextLine() reads that empty newline. Fix: call
[Link]() after nextInt() to consume it.
1. [Link]() reads a complete line including spaces. — [False]
2. BufferedReader is faster than Scanner for large inputs. — [True]
3. Scanner is in [Link] package. — [True]
CHAPTER 13: PATTERN PRINTING
13.1 The Logic Behind Pattern Printing
Almost all patterns use nested loops. The outer loop controls the rows, and the inner loop controls the
columns (characters) per row. Key insight: figure out the relationship between row number (i) and number of
characters (j) printed on that row.
13.2 Square Star Pattern
// n x n square of stars
public class SquarePattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
[Link]("* ");
}
[Link]();
}
}
}
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
13.3 Right Triangle Pattern
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
*
* *
* * *
* * * *
* * * * *
13.4 Inverted Triangle
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
* * * * *
* * * *
* * *
* *
*
13.5 Pyramid (Centered)
int n = 5;
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++) {
[Link](" ");
}
// Print stars
for (int j = 1; j <= 2*i - 1; j++) {
[Link]("*");
}
[Link]();
}
*
***
*****
*******
*********
13.6 Number Triangle
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link]();
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
13.7 Row Number Triangle
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](i + " ");
}
[Link]();
}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
13.8 Alphabet Triangle
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
[Link]((char)('A' + j) + " ");
}
[Link]();
}
A
A B
A B C
A B C D
A B C D E
13.9 Hollow Square
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i==1 || i==n || j==1 || j==n) {
[Link]("* ");
} else {
[Link](" ");
}
}
[Link]();
}
* * * * *
* *
* *
* *
* * * * *
13.10 Diamond Pattern
int n = 5;
// Upper half
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) [Link](" ");
for (int j = 1; j <= 2*i - 1; j++) [Link]("*");
[Link]();
}
// Lower half
for (int i = n-1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) [Link](" ");
for (int j = 1; j <= 2*i - 1; j++) [Link]("*");
[Link]();
}
*
***
*****
*******
*********
*******
*****
***
*
13.11 Pattern Printing Tips for Exams
• Always identify: outer loop = rows, inner loop = columns.
• For spaces before stars: spaces = n - i (for pyramid/diamond).
• For centered patterns: stars = 2*i - 1.
• For hollow patterns: print character only on edges (i==1 || i==n || j==1 || j==n).
• Character patterns: use (char)('A' + j) for alphabet patterns.
CHAPTER 14: EXCEPTION HANDLING
14.1 What is an Exception?
An exception is an unexpected event that disrupts normal program execution. In Java, exceptions are
objects. When an error occurs, Java "throws" an exception object, which must be caught and handled to
prevent the program from crashing.
14.2 Exception Hierarchy
All exceptions in Java inherit from Throwable:
• Throwable → Error (serious, usually don't catch) + Exception
• Exception → Checked Exceptions + RuntimeException (Unchecked)
• Checked: IOException, SQLException, FileNotFoundException
• Unchecked (RuntimeException): NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException, ClassCastException, NumberFormatException
14.3 Checked vs Unchecked Exceptions
Feature Checked Unchecked (Runtime)
Checked at Compile time Runtime
Must handle? Yes (compile error if not) No (optional)
Inherits from Exception (not Runtime) RuntimeException
Examples IOException, SQLException NullPointerException, ArithmeticException
Cause External factors (files, DB) Programming mistakes
14.4 try-catch-finally
public class ExceptionDemo {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
[Link]("Trying: " + arr[5]); // Index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught: " + [Link]());
} catch (Exception e) {
[Link]("General exception: " + [Link]());
} finally {
[Link]("Finally: cleanup done.");
}
[Link]("Program continues normally.");
}
}
Caught: Index 5 out of bounds for length 3
Finally: cleanup done.
Program continues normally.
14.5 Multiple catch Blocks
You can have multiple catch blocks. Java matches them top-to-bottom. Always catch more specific
exceptions BEFORE more general ones.
■■ Putting Exception (parent) catch before a specific catch causes a compile error — unreachable catch block!
14.6 throw Keyword
Use throw to manually throw an exception from your code.
public class ThrowDemo {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above. Got: " + age);
}
[Link]("Age is valid: " + age);
}
public static void main(String[] args) {
try {
checkAge(25);
checkAge(15); // This will throw
} catch (IllegalArgumentException e) {
[Link]("Error: " + [Link]());
}
}
}
Age is valid: 25
Error: Age must be 18 or above. Got: 15
14.7 throws Keyword
Use throws in the method signature to declare that a method might throw a checked exception. The caller
must handle it.
import [Link].*;
public class ThrowsDemo {
static void readFile(String path) throws IOException {
// This might throw IOException - we declare it in throws
FileReader fr = new FileReader(path);
}
public static void main(String[] args) {
try {
readFile("[Link]");
} catch (IOException e) {
[Link]("File error: " + [Link]());
}
}
}
14.8 throw vs throws Comparison
Feature throw throws
Purpose Actually throws an exception Declares possible exception
Location Inside method body In method signature
Followed by Exception object Exception class name(s)
Used for Checked + Unchecked Usually Checked
14.9 Custom Exception
// Define custom exception
class InsufficientFundsException extends Exception {
private double amount;
InsufficientFundsException(double amount) {
super("Insufficient funds! Needed: " + amount);
[Link] = amount;
}
double getAmount() { return amount; }
}
class BankAccount2 {
private double balance;
BankAccount2(double balance) { [Link] = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
[Link]("Withdrawn: " + amount + " | Balance: " + balance);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
BankAccount2 acc = new BankAccount2(500);
try {
[Link](200);
[Link](400); // Will fail
} catch (InsufficientFundsException e) {
[Link]("Error: " + [Link]());
}
}
}
Withdrawn: 200.0 | Balance: 300.0
Error: Insufficient funds! Needed: 100.0
14.10 Exam Questions
Q1. What is the difference between throw and throws?
Ans: throw is used to actually throw an exception object inside a method. throws is used in method signature
to declare that the method might throw certain exceptions.
Q2. What is a checked exception?
Ans: A checked exception is one that is checked at compile time. The programmer MUST handle it with
try-catch or declare it with throws, or the code won't compile.
Q3. Can a finally block change the return value of a method?
Ans: Yes! If finally has a return statement, it overrides the return statement in try. This is considered bad
practice.
1. throws keyword throws an exception. — [False]
2. NullPointerException is a checked exception. — [False]
3. A custom exception class should extend Exception or RuntimeException. — [True]
4. Multiple catch blocks are allowed for one try block. — [True]
5. finally block runs even when return is in try block. — [True]
PART 4: MULTITHREADING
CHAPTER 15: MULTITHREADING — CONCEPTS &
LIFECYCLE
15.1 Process vs Thread
Feature Process Thread
Definition Program in execution Smallest unit of a process
Memory Separate memory space Shares process memory
Communication Inter-process communication (costly) Direct shared memory (easy)
Creation Heavy (new process = new memory) Lightweight
Example Running Chrome browser Each tab in Chrome
15.2 Why Multithreading?
• Better CPU utilization — while one thread waits (e.g., for I/O), another runs.
• Faster programs — multiple tasks run in parallel.
• Better user experience — UI thread stays responsive while background threads work.
• Used in: web servers, games, file downloading, real-time applications.
15.3 Main Thread
Every Java program has at least one thread — the main thread. It is created by JVM when the program
starts and executes the main() method. All other threads are created from this main thread.
public class MainThreadDemo {
public static void main(String[] args) {
Thread t = [Link]();
[Link]("Current thread: " + [Link]());
[Link]("Thread priority: " + [Link]());
[Link]("MyMainThread");
[Link]("Renamed to: " + [Link]());
}
}
Current thread: main
Thread priority: 5
Renamed to: MyMainThread
15.4 Thread Lifecycle (States)
A thread goes through the following states:
State Description
NEW Thread created but start() not yet called
RUNNABLE Thread is ready to run or is running
BLOCKED Thread is waiting for a monitor lock
WAITING Thread is waiting indefinitely (e.g., wait())
TIMED_WAITING Thread waiting for specified time (e.g., sleep(ms))
TERMINATED Thread has finished execution
15.5 start() vs run()
start() run()
Creates a new thread and calls run() in it Executes run() in the CURRENT thread (no new thread)
Asynchronous — does not wait Synchronous — waits for run() to finish
Thread enters RUNNABLE state No multithreading — just a regular method call
Use this for actual multithreading Do NOT use this if you want multithreading
■■ A very common exam question: If you call run() instead of start(), no new thread is created! The code runs on
the main thread sequentially.
CHAPTER 16: sleep() METHOD
16.1 Definition
[Link](milliseconds) is a static method that pauses the execution of the current thread for a
specified time. The thread enters TIMED_WAITING state. Other threads can run during this pause.
16.2 Syntax
[Link](1000); // Sleep for 1 second (1000 ms)
[Link](500); // Sleep for 0.5 seconds
// sleep() can throw InterruptedException (checked)
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
16.3 Code Example with sleep()
public class SleepDemo {
public static void main(String[] args) {
[Link]("Start - " + [Link]());
try {
[Link]("Sleeping for 2 seconds...");
[Link](2000); // pause 2 seconds
[Link]("Awake! - " + [Link]());
} catch (InterruptedException e) {
[Link]("Interrupted: " + [Link]());
}
[Link]("Program ends.");
}
}
Start - 1715167200000
Sleeping for 2 seconds...
Awake! - 1715167202001
Program ends.
16.4 sleep() in Multithreading
class CountThread extends Thread {
String name;
CountThread(String name) { [Link] = name; }
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](name + " - Count: " + i);
try {
[Link](500); // Each count pauses 0.5s
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class SleepMultiDemo {
public static void main(String[] args) throws InterruptedException {
CountThread t1 = new CountThread("Thread-A");
CountThread t2 = new CountThread("Thread-B");
[Link]();
[Link]();
}
}
Thread-A - Count: 1
Thread-B - Count: 1
Thread-A - Count: 2
Thread-B - Count: 2
Thread-A - Count: 3
Thread-B - Count: 3
(Note: actual order may vary - threads are concurrent!)
16.5 Key Points about sleep()
• static method — called as [Link](), not on an object.
• Throws InterruptedException — must be handled.
• Does NOT release any locks (if thread holds a synchronized lock, it keeps it during sleep).
• Other threads can execute while one thread is sleeping.
• Thread goes to TIMED_WAITING state during sleep.
16.6 Exam Questions
Q1. Does sleep() release locks?
Ans: No. [Link]() does NOT release any synchronized locks. The sleeping thread keeps all its locks
during sleep.
Q2. What exception does sleep() throw?
Ans: InterruptedException — a checked exception that must be handled.
1. [Link]() releases synchronized locks during sleep. — [False]
2. sleep() is a static method. — [True]
3. [Link](1000) pauses the thread for 1 second. — [True]
4. InterruptedException is an unchecked exception. — [False]
CHAPTER 17: MULTITHREADING WITH Thread
CLASS
17.1 Creating a Thread by Extending Thread
The first way to create a thread is to extend the Thread class and override its run() method.
17.2 Steps:
1. Create a class that extends Thread.
2. Override the run() method with the code to execute.
3. Create an object of your class.
4. Call start() on the object (not run()!).
17.3 Complete Example
class PrintThread extends Thread {
String threadName;
int count;
PrintThread(String name, int count) {
[Link] = name;
[Link] = count;
}
@Override
public void run() {
for (int i = 1; i <= count; i++) {
[Link](threadName + " -> " + i);
try {
[Link](300);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
[Link](threadName + " DONE.");
}
}
public class ThreadClassDemo {
public static void main(String[] args) {
PrintThread t1 = new PrintThread("Worker-1", 3);
PrintThread t2 = new PrintThread("Worker-2", 3);
PrintThread t3 = new PrintThread("Worker-3", 3);
[Link]("Starting all threads...");
[Link]();
[Link]();
[Link]();
[Link]("All threads started (main continues).");
}
}
Starting all threads...
All threads started (main continues).
Worker-1 -> 1
Worker-2 -> 1
Worker-3 -> 1
Worker-1 -> 2
Worker-2 -> 2
Worker-3 -> 2
Worker-1 -> 3
Worker-3 -> 3
Worker-2 -> 3
Worker-1 DONE.
Worker-3 DONE.
Worker-2 DONE.
(Output order may vary — threads run concurrently!)
17.4 Thread Properties
class InfoThread extends Thread {
public void run() {
[Link]("Name: " + getName());
[Link]("ID: " + getId());
[Link]("Priority: " + getPriority());
[Link]("Is Alive: " + isAlive());
}
}
public class ThreadPropertiesDemo {
public static void main(String[] args) throws InterruptedException {
InfoThread t = new InfoThread();
[Link]("MyThread");
[Link](Thread.MAX_PRIORITY); // priority 10
[Link]("Before start - isAlive: " + [Link]());
[Link]();
[Link](100);
[Link]("After start - isAlive: " + [Link]());
}
}
Before start - isAlive: false
Name: MyThread
ID: 12
Priority: 10
Is Alive: true
After start - isAlive: false
17.5 Disadvantage of extends Thread
■■ If your class already extends another class, it CANNOT also extend Thread (Java doesn't support multiple
class inheritance). In that case, use the Runnable interface.
17.6 Exam Questions
Q1. What method do you override when extending Thread?
Ans: You override the run() method, which contains the code to be executed by the new thread.
Q2. Why should we call start() and not run() directly?
Ans: Calling start() creates a new thread and executes run() in that new thread. Calling run() directly just
executes it in the current thread — no multithreading happens.
1. You must override the start() method when extending Thread. — [False]
2. A Thread class object can be restarted after it terminates. — [False]
3. Thread priorities can be set between 1 and 10. — [True]
CHAPTER 18: MULTITHREADING WITH Runnable
INTERFACE
18.1 Why Runnable?
The Runnable interface provides a second way to create threads. Since Java does not support multiple class
inheritance, if your class already extends another class, you CANNOT extend Thread. Using Runnable
solves this — your class can implement Runnable and still extend something else.
18.2 Steps:
1. Create a class that implements Runnable.
2. Implement the run() method.
3. Create a Thread object, passing your Runnable as argument.
4. Call start() on the Thread object.
18.3 Complete Example
class PrintTask implements Runnable {
String taskName;
int count;
PrintTask(String name, int count) {
[Link] = name;
[Link] = count;
}
@Override
public void run() {
for (int i = 1; i <= count; i++) {
[Link](taskName + " -> " + i);
try {
[Link](200);
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
[Link](taskName + " COMPLETED.");
}
}
public class RunnableDemo {
public static void main(String[] args) {
// Create Runnable objects
PrintTask task1 = new PrintTask("DownloadFile", 3);
PrintTask task2 = new PrintTask("SaveData", 3);
// Wrap in Thread objects
Thread t1 = new Thread(task1);
Thread t2 = new Thread(task2);
[Link]("DownloadThread");
[Link]("SaveThread");
// Start threads
[Link]();
[Link]();
[Link]("Main thread: tasks dispatched.");
}
}
Main thread: tasks dispatched.
DownloadFile -> 1
SaveData -> 1
DownloadFile -> 2
SaveData -> 2
DownloadFile -> 3
SaveData -> 3
DownloadFile COMPLETED.
SaveData COMPLETED.
(Exact order may vary)
18.4 Lambda with Runnable (Java 8+)
Since Runnable is a functional interface (single abstract method), you can use a lambda expression:
public class LambdaThreadDemo {
public static void main(String[] args) {
// Runnable as lambda
Runnable r = () -> {
for (int i = 1; i <= 3; i++) {
[Link]([Link]().getName() + " - " + i);
}
};
Thread t1 = new Thread(r, "LambdaThread-1");
Thread t2 = new Thread(r, "LambdaThread-2");
[Link]();
[Link]();
}
}
18.5 Extends Thread vs Implements Runnable
Feature extends Thread implements Runnable
Inheritance Uses up inheritance slot Free to extend other classes
Object type IS-A Thread HAS-A Thread (more flexible)
Reusability One class, one thread concept Same Runnable can be shared across threads
OOP principle Tight coupling Loose coupling (preferred)
Lambda support No Yes (functional interface)
Recommended? Simple cases Almost always preferred
■ Always prefer Runnable over extending Thread in real-world code. Runnable is more flexible, decouples task
from thread management, and follows better OOP design.
18.6 Exam Questions
Q1. Why is Runnable preferred over extending Thread?
Ans: Because (1) Java doesn't support multiple inheritance — your class might already extend something, (2)
Runnable separates task from thread management, (3) the same Runnable can be used by multiple threads,
(4) supports lambda expressions.
Q2. How do you create a Thread using Runnable?
Ans: Implement Runnable and its run() method. Then create a Thread object passing the Runnable: Thread t
= new Thread(runnableObject); Then call [Link]();
1. Runnable interface has two abstract methods. — [False]
2. implements Runnable allows a class to extend another class. — [True]
3. Thread t = new Thread(runnableObj); [Link](); creates a new thread. — [False]
4. Runnable is a functional interface. — [True]
CHAPTER 19: join() METHOD
19.1 Definition
The join() method causes the current (calling) thread to wait until the thread on which join() was called
finishes its execution. It ensures sequential completion of threads when needed.
19.2 Real-Life Analogy
Imagine you're a manager (main thread). You assign tasks to two employees (threads). You use join() to say:
"I will NOT move forward until you finish your work." join() is like "wait for this employee to finish before I
continue."
19.3 Syntax
Thread t = new Thread(someTask);
[Link]();
[Link](); // Main thread waits here until t finishes
// Code here runs AFTER t has finished
19.4 Without join() — Problem
class DataProcessor extends Thread {
int[] result = new int[1];
public void run() {
try { [Link](1000); } catch (InterruptedException e) {}
result[0] = 42;
[Link]("Processor done. Result = " + result[0]);
}
}
public class WithoutJoinDemo {
public static void main(String[] args) {
DataProcessor dp = new DataProcessor();
[Link]();
// Problem: main doesn't wait - result[0] is still 0 here!
[Link]("Main: Result = " + [Link][0]);
}
}
Main: Result = 0
Processor done. Result = 42
■■ Main thread printed 0 because it didn't wait for DataProcessor to finish!
19.5 With join() — Solution
public class WithJoinDemo {
public static void main(String[] args) throws InterruptedException {
DataProcessor dp = new DataProcessor();
[Link]();
[Link](); // Main waits for dp to finish
[Link]("Main: Result = " + [Link][0]); // Now correct!
}
}
Processor done. Result = 42
Main: Result = 42
19.6 join() with Multiple Threads
class Worker extends Thread {
String task;
Worker(String task) { [Link] = task; }
public void run() {
[Link]("Starting: " + task);
try { [Link](500); } catch (InterruptedException e) {}
[Link]("Done: " + task);
}
}
public class JoinMultiDemo {
public static void main(String[] args) throws InterruptedException {
Worker w1 = new Worker("Download");
Worker w2 = new Worker("Process");
Worker w3 = new Worker("Upload");
[Link]();
[Link](); // Wait for download to finish
[Link]();
[Link](); // Wait for processing
[Link]();
[Link](); // Wait for upload
[Link]("All tasks completed in sequence!");
}
}
Starting: Download
Done: Download
Starting: Process
Done: Process
Starting: Upload
Done: Upload
All tasks completed in sequence!
19.7 join(millis) — Timed Join
join(long millis) waits for the thread to finish, but only for the specified milliseconds. If thread doesn't finish in
time, main continues anyway.
[Link](2000); // Wait up to 2 seconds, then continue regardless
19.8 Common Mistakes
■■ Calling join() before start() — causes IllegalThreadStateException.
■■ Forgetting to handle InterruptedException that join() throws.
■■ Using join() when you actually want threads to run in parallel — join() forces sequential execution.
19.9 sleep() vs join() Comparison
Feature sleep() join()
Purpose Pause current thread for time Wait for another thread to finish
Argument Milliseconds Optionally milliseconds
Static? Yes — [Link]() No — [Link]() on object
Returns when Time expires Thread finishes (or time expires)
Exception InterruptedException InterruptedException
19.10 Exam Questions
Q1. What does join() do?
Ans: join() makes the calling thread wait until the thread on which join() is called completes its execution.
Q2. What is the difference between sleep() and join()?
Ans: sleep() pauses a thread for a specified time. join() makes a thread wait for another specific thread to
finish.
Q3. What exception does join() throw?
Ans: InterruptedException — same as sleep().
1. join() pauses a thread for a specified number of milliseconds. — [False]
2. join() must be called after start(). — [True]
3. join() is a static method like sleep(). — [False]
4. join(2000) will wait at most 2 seconds for the thread. — [True]
PART 5: COMPLETE QUESTION BANK
SECTION A: 100+ ONE-MARK QUESTIONS
Q1. What does OOP stand for?
Ans: Object-Oriented Programming
Q2. Name the 4 pillars of OOP.
Ans: Polymorphism, Encapsulation, Inheritance, Abstraction
Q3. What keyword is used for inheritance in Java?
Ans: extends
Q4. What keyword is used to implement an interface?
Ans: implements
Q5. What does abstract keyword do?
Ans: Marks a class/method as abstract — class cannot be instantiated, method has no body
Q6. Can an abstract class be instantiated?
Ans: No
Q7. What is the purpose of final keyword for a variable?
Ans: Makes it a constant — value cannot be changed
Q8. Can you override a final method?
Ans: No
Q9. Can you extend a final class?
Ans: No
Q10. What does static mean?
Ans: Member belongs to the class, not to objects
Q11. Can a static method access instance variables?
Ans: Not directly — needs an object reference
Q12. What does this keyword refer to?
Ans: Current object (instance)
Q13. What must this() be in a constructor?
Ans: The first statement
Q14. What does super() do?
Ans: Calls the parent class constructor
Q15. When does a static block execute?
Ans: Once, when the class is first loaded
Q16. When does an instance block execute?
Ans: Before every constructor call
Q17. What is the most restrictive access modifier?
Ans: private
Q18. What is the least restrictive access modifier?
Ans: public
Q19. What does protected allow?
Ans: Access within same package and by subclasses
Q20. What is default access?
Ans: Package-private — accessible only within same package
Q21. What Scanner method reads an integer?
Ans: nextInt()
Q22. What Scanner method reads a full line?
Ans: nextLine()
Q23. What Scanner method reads a single word?
Ans: next()
Q24. What is the bug after nextInt()?
Ans: Leftover newline in buffer makes next nextLine() return empty string
Q25. What package is Scanner in?
Ans: [Link]
Q26. What does [Link](1000) do?
Ans: Pauses the current thread for 1000 milliseconds (1 second)
Q27. What exception does sleep() throw?
Ans: InterruptedException
Q28. What is the purpose of start() method?
Ans: Creates a new thread and calls run() in that thread
Q29. What happens if you call run() instead of start()?
Ans: No new thread is created — runs on current thread
Q30. What interface do you implement for multithreading?
Ans: Runnable
Q31. What method do you override in Runnable?
Ans: run()
Q32. What does join() do?
Ans: Makes calling thread wait until the joined thread finishes
Q33. Is join() a static method?
Ans: No
Q34. Is sleep() a static method?
Ans: Yes
Q35. What is a checked exception?
Ans: Exception checked at compile time — must handle or declare with throws
Q36. What is an unchecked exception?
Ans: RuntimeException — not checked at compile time
Q37. What does throw keyword do?
Ans: Throws an exception object manually
Q38. What does throws keyword do?
Ans: Declares that a method may throw certain exceptions
Q39. Does finally block always execute?
Ans: Almost always — except [Link]() or JVM crash
Q40. What is encapsulation?
Ans: Bundling data and methods, hiding fields with private + getters/setters
Q41. What is polymorphism?
Ans: One name, many forms — method can behave differently based on context
Q42. What is method overloading?
Ans: Same method name, different parameters in the same class
Q43. What is method overriding?
Ans: Same method signature in parent and child class — child provides its own version
Q44. When is overloading resolved?
Ans: Compile time
Q45. When is overriding resolved?
Ans: Runtime
Q46. What is upcasting?
Ans: Assigning child object to parent reference — implicit
Q47. What is downcasting?
Ans: Casting parent reference back to child — explicit
Q48. What is dynamic method dispatch?
Ans: JVM decides which overridden method to call at runtime based on actual object type
Q49. Can interface have constructors?
Ans: No
Q50. What are interface variables by default?
Ans: public static final
Q51. What are interface methods by default?
Ans: public abstract
Q52. Can a class implement multiple interfaces?
Ans: Yes
Q53. What keyword does interface use to extend another interface?
Ans: extends
Q54. What is the Diamond Problem?
Ans: Ambiguity when a class inherits from two classes with same method
Q55. How does Java solve Diamond Problem?
Ans: By not allowing multiple class inheritance; uses interfaces instead
Q56. What is method hiding?
Ans: A child class defines a static method with same signature as parent's static method
Q57. Can private methods be inherited?
Ans: No
Q58. What thread state is during sleep()?
Ans: TIMED_WAITING
Q59. What thread state after start() before getting CPU?
Ans: RUNNABLE
Q60. What thread state when execution finishes?
Ans: TERMINATED
Q61. What is the default thread priority?
Ans: 5 (NORM_PRIORITY)
Q62. What is MAX_PRIORITY value?
Ans: 10
Q63. What is MIN_PRIORITY value?
Ans: 1
Q64. What is finalize() method?
Ans: Called by garbage collector before object is destroyed (deprecated)
Q65. What is the difference between final, finally, finalize?
Ans: final=modifier, finally=exception block, finalize()=GC method
Q66. Can you have try without catch?
Ans: Yes, if you have finally: try { } finally { }
Q67. What is a custom exception?
Ans: User-defined exception class extending Exception or RuntimeException
Q68. What is NullPointerException?
Ans: Thrown when you try to use a null object reference
Q69. What is ArrayIndexOutOfBoundsException?
Ans: Thrown when array index is out of valid range
Q70. What is ClassCastException?
Ans: Thrown when invalid downcast is performed
Q71. What is NumberFormatException?
Ans: Thrown when String cannot be parsed to a number (e.g., [Link]('abc'))
Q72. What is a constructor?
Ans: A special method with same name as class, no return type, initializes objects
Q73. Can constructors be overloaded?
Ans: Yes
Q74. What is a default constructor?
Ans: No-argument constructor — Java provides one if none is written
Q75. What is the return type of a constructor?
Ans: None (not even void)
Q76. What is IS-A relationship?
Ans: Relationship through inheritance — Dog IS-A Animal
Q77. What is HAS-A relationship?
Ans: Composition — Car HAS-A Engine (object as field)
Q78. What is the Object class?
Ans: Root class of all Java classes — every class implicitly extends Object
Q79. Name two methods of Object class.
Ans: toString(), equals(), hashCode(), getClass()
Q80. What is @Override annotation?
Ans: Tells compiler this method overrides parent's method — compile error if not actual override
Q81. Can abstract class have non-abstract methods?
Ans: Yes
Q82. Can we have an abstract method in non-abstract class?
Ans: No — class must be abstract if it has abstract methods
Q83. What is covariant return type?
Ans: An overriding method can return a subtype of the parent method's return type
Q84. What is the main thread in Java?
Ans: The thread JVM creates to execute main() method
Q85. What does [Link]() return?
Ans: Reference to the currently executing thread
Q86. What is getName() in Thread?
Ans: Returns the name of the thread
Q87. What is isAlive()?
Ans: Returns true if thread has been started and not yet terminated
Q88. What is join(2000)?
Ans: Waits up to 2000ms for thread to finish, then continues regardless
Q89. What is the Runnable interface's abstract method?
Ans: void run()
Q90. What is a functional interface?
Ans: An interface with exactly one abstract method — can use lambda expressions
Q91. Is Runnable a functional interface?
Ans: Yes
Q92. What is a lambda expression?
Ans: A concise way to implement a functional interface: () -> { code }
Q93. Does sleep() release synchronized lock?
Ans: No
Q94. What happens if a thread calls join() on itself?
Ans: Deadlock — thread waits for itself to finish — endless wait
Q95. What is IllegalThreadStateException?
Ans: Thrown when operation is not valid for thread's current state, e.g., starting already started thread
Q96. Can interfaces extend multiple interfaces?
Ans: Yes
Q97. What are default methods in interfaces?
Ans: Concrete methods in interfaces (Java 8+) with default keyword
Q98. What is String in Java?
Ans: An immutable, final class — cannot be extended and value cannot be changed
Q99. What is the Scanner class used for?
Ans: Taking input from user via console (keyboard)
Q100. What is BufferedReader?
Ans: A class for efficient character input reading, faster than Scanner for large input
Q101. How do you read a character using Scanner?
Ans: [Link]().charAt(0)
SECTION B: 100+ TRUE/FALSE QUESTIONS
1. Java supports multiple class inheritance. — [False]
2. An abstract class can have a constructor. — [True]
3. Interfaces can be instantiated directly. — [False]
4. Method overloading is resolved at runtime. — [False]
5. Method overriding requires the same method signature. — [True]
6. A final class can be instantiated. — [True]
7. A final class can be extended. — [False]
8. Static methods can access instance variables directly. — [False]
9. this keyword is available in static methods. — [False]
10. super() must be the first statement in a constructor. — [True]
11. Private members are inherited by subclasses. — [False]
12. Protected members can be accessed in subclasses of different packages. — [True]
13. The finally block always executes even after [Link](). — [False]
14. throw is used in method signature. — [False]
15. throws is used inside method body. — [False]
16. NullPointerException is a checked exception. — [False]
17. IOException is a checked exception. — [True]
18. Calling run() directly creates a new thread. — [False]
19. sleep() is an instance method. — [False]
20. join() is a static method. — [False]
21. [Link]() releases synchronized locks. — [False]
22. The default thread priority is 5. — [True]
23. A thread can be restarted after it terminates. — [False]
24. Runnable is a functional interface. — [True]
25. Interface variables are public static final by default. — [True]
26. An interface can extend multiple interfaces. — [True]
27. A class can extend multiple abstract classes. — [False]
28. @Override annotation is mandatory. — [False]
29. Overloading can differ only in return type. — [False]
30. Covariant return type is allowed in overriding. — [True]
31. Constructors can be overloaded. — [True]
32. Constructor has a return type of void. — [False]
33. Default constructor is provided if no constructor is written. — [True]
34. Static block runs once when class is loaded. — [True]
35. Instance block runs before constructor. — [True]
36. Static block can access instance variables. — [False]
37. BufferedReader is faster than Scanner for large input. — [True]
38. next() reads a complete line. — [False]
39. nextLine() reads up to but not including newline. — [True]
40. Scanner is in [Link] package. — [False]
41. Multiple catch blocks can follow one try. — [True]
42. Custom exceptions must extend RuntimeException. — [False]
43. A try block can exist with only finally (no catch). — [True]
44. join(2000) waits indefinitely for thread to finish. — [False]
45. The main thread is created by JVM automatically. — [True]
46. InterruptedException is a checked exception. — [True]
47. Dynamic method dispatch is based on declared type. — [False]
48. Upcasting is explicit in Java. — [False]
49. Downcasting is implicit in Java. — [False]
50. Abstract methods have a method body. — [False]
51. An interface method can be private in Java 9+. — [True]
52. Default methods in interfaces can be overridden. — [True]
53. String class is final in Java. — [True]
54. finalize() is called explicitly by the programmer. — [False]
55. A class with no abstract methods can still be abstract. — [True]
56. protected keyword allows access from any class anywhere. — [False]
57. Default access modifier allows access from different packages. — [False]
58. static keyword can be used with local variables inside methods. — [False]
59. A method can have multiple throws declarations. — [True]
60. Polymorphism only works with inheritance. — [False]
61. Overriding cannot reduce the visibility of the method. — [True]
62. this() can be called from anywhere in a constructor. — [False]
63. An abstract class must have at least one abstract method. — [False]
64. Interface can have static methods in Java 8+. — [True]
65. Multithreading improves CPU utilization. — [True]
66. Thread priority guarantees execution order. — [False]
67. Two threads with same priority always run in round-robin. — [False]
68. TERMINATED state means thread finished execution. — [True]
69. BLOCKED state means thread is sleeping. — [False]
70. start() can be called multiple times on same thread. — [False]
71. Lambda expressions can implement Runnable. — [True]
72. Encapsulation hides implementation details. — [False]
73. Abstraction hides implementation details. — [True]
74. Encapsulation uses private fields and public methods. — [True]
75. Method overriding is an example of compile-time polymorphism. — [False]
76. Method overloading is an example of runtime polymorphism. — [False]
77. Inheritance promotes code reuse. — [True]
78. HAS-A is achieved through composition, not inheritance. — [True]
79. Object class is the root of all Java classes. — [True]
80. equals() and hashCode() are from Object class. — [True]
81. abstract keyword can appear before any variable. — [False]
82. final variables must be initialized at declaration. — [False]
83. [Link]() should be called when done. — [True]
84. join() can throw InterruptedException. — [True]
85. sleep() can be called on any thread from outside. — [False]
86. Multiple static blocks are executed in order. — [True]
87. An interface can implement another interface. — [False]
88. A class can be both abstract and final. — [False]
89. Interfaces support multiple inheritance. — [True]
90. Private constructor prevents object creation from outside. — [True]
91. The Runnable interface method takes arguments. — [False]
92. Constructor chaining is done with this(). — [True]
93. super() calls parent's method. — [False]
94. [Link]() calls parent's method. — [True]
95. A thread in WAITING state is waiting for notification. — [True]
96. sleep() pauses all threads simultaneously. — [False]
97. IllegalThreadStateException is thrown when starting a terminated thread. — [True]
98. Checked exceptions must be handled at compile time. — [True]
99. ArithmeticException is a checked exception. — [False]
100. ClassCastException is thrown on invalid downcast. — [True]
101. Interface default methods solve the Diamond Problem for interfaces. — [True]
SECTION C: 50+ MCQ QUESTIONS
1. Which of the following is NOT a pillar of OOP?
(A) Polymorphism
✓ (B) Compilation
(C) Inheritance
(D) Encapsulation
2. Method overloading is resolved at:
(A) Runtime
✓ (B) Compile time
(C) Link time
(D) Load time
3. Which keyword is used for inheritance?
(A) implements
(B) inherits
✓ (C) extends
(D) super
4. Which access modifier has widest visibility?
(A) private
(B) protected
(C) default
✓ (D) public
5. What is the output of: int x=5; final int y=x; y=10;
(A) 10
(B) 5
✓ (C) Compile error
(D) Runtime error
6. Which of these cannot be overridden?
(A) public method
(B) protected method
✓ (C) private method
(D) abstract method
7. What does super() do?
(A) Calls superclass method
✓ (B) Calls superclass constructor
(C) Accesses superclass variable
(D) All of above
8. When does static block execute?
(A) When object is created
✓ (B) When class is loaded
(C) When method is called
(D) When constructor runs
9. Which interface method for Runnable must be implemented?
(A) start()
(B) execute()
✓ (C) run()
(D) begin()
10. What exception does [Link]() throw?
(A) IOException
(B) RuntimeException
✓ (C) InterruptedException
(D) ThreadException
11. Which is true about static methods?
(A) Can use this
(B) Can access instance vars
✓ (C) Cannot be overridden (only hidden)
(D) Can be called on instance only
12. What is the default priority of a thread?
(A) 1
(B) 3
✓ (C) 5
(D) 10
13. Which of these is a checked exception?
(A) NullPointerException
(B) ArrayIndexOutOfBoundsException
✓ (C) IOException
(D) ArithmeticException
14. What keyword manually throws an exception?
(A) throws
✓ (B) throw
(C) catch
(D) raise
15. What does join() do?
(A) Pauses thread for given time
✓ (B) Makes calling thread wait for another to finish
(C) Combines two threads
(D) Starts a thread
16. Which is correct to create thread using Runnable?
(A) Thread t = new Runnable()
(B) Runnable r = new Thread()
✓ (C) Thread t = new Thread(runnable); [Link]()
(D) [Link]()
17. Which block always executes in exception handling?
(A) try
(B) catch
✓ (C) finally
(D) throw
18. Abstract class differs from interface because:
(A) Cannot be instantiated
✓ (B) Can have constructors and concrete methods
(C) Cannot have methods
(D) Only supports public access
19. What does this() do?
(A) Refers to current object
✓ (B) Calls current class's constructor
(C) Calls parent constructor
(D) Returns current class
20. Which is NOT true about interfaces?
(A) Can have default methods (Java 8+)
✓ (B) Can have constructors
(C) Can extend multiple interfaces
(D) Variables are public static final
21. What is dynamic method dispatch?
(A) Choosing method at compile time
(B) Choosing overloaded method
✓ (C) Calling overridden method based on actual object at runtime
(D) Dispatching threads
22. What is the correct order of execution?
(A) Constructor → Static block → Instance block
✓ (B) Static block → Instance block → Constructor
(C) Instance block → Static block → Constructor
(D) Static block → Constructor → Instance block
23. Which modifier allows access in subclass but not different-package non-subclass?
(A) public
(B) private
✓ (C) protected
(D) default
24. Scanner class is in which package?
(A) [Link]
(B) [Link]
✓ (C) [Link]
(D) [Link]
25. Which reads a whole line including spaces?
(A) next()
(B) nextToken()
✓ (C) nextLine()
(D) readLine()
26. What is the bug with nextInt() followed by nextLine()?
(A) nextInt() crashes
✓ (B) nextLine() skips input by reading leftover newline
(C) nextInt() reads wrong type
(D) Both read same value
27. Which is an example of compile-time polymorphism?
(A) Method overriding
(B) Dynamic dispatch
✓ (C) Method overloading
(D) Upcasting
28. Upcasting in Java is:
(A) Explicit and unsafe
✓ (B) Implicit and safe
(C) Only possible with interfaces
(D) Requires cast operator
29. Which state is a thread in when join() is waiting?
(A) BLOCKED
(B) SLEEPING
✓ (C) WAITING
(D) RUNNABLE
30. What does isAlive() return for a terminated thread?
(A) true
✓ (B) false
(C) null
(D) -1
31. Which of these can be abstract?
(A) Variables
(B) Constructors
✓ (C) Methods
(D) Packages
32. final + abstract combination for a method is:
(A) Valid
✓ (B) Invalid — contradictory
(C) Valid only in interface
(D) Valid only in abstract class
33. Which is correct for encapsulation?
(A) Make fields public
✓ (B) Make fields private with public getters/setters
(C) Use abstract methods
(D) Use static methods only
34. What is the keyword to declare a constant in Java?
(A) const
(B) #define
✓ (C) final
(D) static
35. [Link]() affects:
(A) All threads
✓ (B) The calling thread only
(C) The next thread to run
(D) The main thread only
36. Which exception is thrown on invalid array index?
(A) IndexException
(B) ArrayException
✓ (C) ArrayIndexOutOfBoundsException
(D) InvalidIndexException
37. What is the parent of all Java classes?
(A) Class
(B) Void
✓ (C) Object
(D) Super
38. Which statement about constructors is TRUE?
(A) Constructor returns void
✓ (B) Constructor has same name as class
(C) Constructor can be abstract
(D) Constructor can be static
39. How many abstract methods can Runnable have?
(A) 0
✓ (B) 1
(C) 2
(D) Many
40. In which Java version were default methods in interfaces added?
(A) Java 5
(B) Java 6
(C) Java 7
✓ (D) Java 8
41. What is method hiding?
(A) Hiding method from user
(B) Overriding static method
✓ (C) Static method in child with same signature as parent static
(D) Making method private
42. Which exception is thrown on [Link]()?
(A) NullException
✓ (B) NullPointerException
(C) NullAccessException
(D) NoObjectException
43. What does start() do?
(A) Runs run() in current thread
✓ (B) Creates new thread and calls run() in it
(C) Starts the JVM
(D) Initializes the thread object
44. Which is true about interface variables?
(A) Can be changed
(B) Are instance variables
✓ (C) Are public static final
(D) Can be private
45. Protected access allows access from:
(A) Same class only
✓ (B) Same package and subclasses
(C) Any class
(D) Same class and same package only
46. What is the main advantage of Runnable over Thread?
(A) Runnable is faster
✓ (B) Runnable allows class to extend another class
(C) Runnable has more methods
(D) Runnable is older
47. What happens when [Link](0) is called in try?
(A) finally runs
✓ (B) finally doesn't run
(C) catch runs
(D) Program throws exception
48. What is NumberFormatException?
(A) Checked exception
(B) Thrown when number is too large
✓ (C) Thrown when String cannot be parsed to number
(D) IOException subclass
49. To avoid nextInt() buffer issue, you should:
(A) Use nextLine() only
✓ (B) Call [Link]() after nextInt() to flush buffer
(C) Restart Scanner
(D) Use BufferedReader always
50. Which threading method forces sequential execution?
(A) sleep()
(B) start()
✓ (C) join()
(D) run()
SECTION D: BRAINSTORMING & CREATIVE
QUESTIONS
Q1. Design a Java class hierarchy for a School Management System using all 4 OOP pillars. Describe
classes, relationships, and abstract methods.
Q2. Explain how you would use polymorphism to write a single method that can process Circle, Rectangle,
and Triangle objects differently.
Q3. If Java allowed multiple class inheritance, what problems could arise? Design a scenario
demonstrating the Diamond Problem.
Q4. Design a thread-safe BankAccount class where two threads (deposit and withdraw) operate
concurrently. What issues could arise?
Q5. Explain why Runnable is better than extends Thread using a real-world scenario where your class
already inherits from another.
Q6. Design a custom exception hierarchy for an online shopping system: PaymentException,
InsufficientFundsException, InvalidCardException.
Q7. How would you implement a countdown timer using multithreading? Write the design and logic.
Q8. Explain the difference between compile-time and runtime polymorphism using a Shape drawing
application.
Q9. If you had to redesign Java's access modifiers, what changes would you make and why?
Q10. Design a thread pool simulation where 5 workers process 10 tasks. How would you manage threads?
Q11. Explain how encapsulation protects data using a real medical records system example.
Q12. Compare static block vs static method — when would you use each?
Q13. Design an interface hierarchy for different types of vehicles: Flyable, Drivable, Swimmable.
Q14. What is the Builder pattern? How does it use the 'return this' feature of the this keyword?
Q15. Explain how the Java String class uses final class and immutability. Why is it designed this way?
Q16. Design a simulation of a restaurant order system using multithreading (Chef thread, Server thread).
Q17. How would you implement a generic stack using encapsulation and exception handling?
Q18. Explain why abstract classes exist when interfaces can do most of the same things.
Q19. Design a logging system that uses static methods and a static counter.
Q20. What are the implications of calling join() in a GUI application? Could it freeze the UI?
Q21. Compare Scanner and BufferedReader. In which scenarios would each be preferable?
Q22. Design a car rental system using inheritance, encapsulation, and exception handling.
Q23. Explain how dynamic method dispatch enables the Open/Closed principle of SOLID design.
Q24. Design a simple game (like tic-tac-toe) where game logic and UI run on separate threads.
Q25. If you want a class to be completely immutable (like String), what Java features would you use?
Q26. Design a class using both interfaces and abstract classes for a payment processing system.
Q27. How would you test if multithreading code is correct? What scenarios would you test?
Q28. Explain the lifecycle of a thread from creation to termination with a real example.
Q29. Design an employee management system demonstrating all access modifiers meaningfully.
Q30. Write a design for a multi-level exception handling system for a web application.
SECTION E: SHORT CODING QUESTIONS
Q1. Write a Java program demonstrating method overloading with 3 versions of calculate() method.
Q2. Write a program showing runtime polymorphism using Animal → Dog, Cat, Bird.
Q3. Create an encapsulated Person class with private name, age and proper getters/setters with
validation.
Q4. Write a program showing multilevel inheritance: Vehicle → Car → ElectricCar.
Q5. Create an abstract class Shape with abstract area() and perimeter(), implement for Circle and
Rectangle.
Q6. Write a Java interface Sortable with a sort() method. Implement it in BubbleSorter and SelectionSorter.
Q7. Demonstrate the use of final variable, final method, and final class in one program.
Q8. Write a program showing static variable (shared counter) and static method.
Q9. Demonstrate this keyword for variable shadowing and constructor chaining.
Q10. Show the execution order of static block, instance block, and constructor with two objects.
Q11. Write a program showing all 4 access modifiers with appropriate classes.
Q12. Write a Scanner program that takes name, age, GPA and prints a formatted student report.
Q13. Write a program to print a hollow diamond pattern of size n.
Q14. Print the Pascal's triangle for n rows.
Q15. Write a program with try-catch-finally that handles ArrayIndexOutOfBoundsException.
Q16. Create a custom exception AgeNotValidException and use it in a Voter eligibility checker.
Q17. Write a multithreaded program where Thread A prints odd numbers and Thread B prints even
numbers.
Q18. Write a program using Runnable interface where two tasks run concurrently.
Q19. Write a program demonstrating join() to ensure threads execute in a specific sequence.
Q20. Write a program where a thread sleeps for 2 seconds between printing messages.
Q21. Demonstrate upcasting and downcasting with a parent-child class example.
Q22. Write a program showing how interface solves multiple inheritance.
Q23. Create a Java program simulating a bank with deposit, withdraw, and custom exceptions.
Q24. Write a program showing default method conflict resolution in interfaces.
Q25. Implement a simple countdown from 10 to 1 using a separate thread and sleep().
Q26. Write a program that takes an integer array from Scanner and prints all patterns.
Q27. Demonstrate BufferedReader for taking multiple lines of input.
Q28. Create an abstract Employee class with concrete getSalary() and abstract getDepartment().
Q29. Write a class showing constructor overloading with 3 different constructors.
Q30. Write a multithreaded program using lambda (Runnable as lambda) to print 'Hello' 5 times.
SECTION F: OUTPUT TRACING QUESTIONS
For each program, determine the exact output:
Question 1: What is the output?
class A {
static { [Link]("A-static"); }
{ [Link]("A-instance"); }
A() { [Link]("A-constructor"); }
}
class B extends A {
static { [Link]("B-static"); }
{ [Link]("B-instance"); }
B() { [Link]("B-constructor"); }
}
public class Test {
public static void main(String[] args) {
new B(); new B();
}
}
Answer:
A-static
B-static
A-instance
A-constructor
B-instance
B-constructor
A-instance
A-constructor
B-instance
B-constructor
Question 2: What is the output?
public class OverloadTest {
static void show(int x) { [Link]("int: " + x); }
static void show(double x) { [Link]("double: " + x); }
static void show(String x) { [Link]("String: " + x); }
public static void main(String[] args) {
show(5); show(3.14); show("Hi"); show('A');
}
}
Answer:
int: 5
double: 3.14
String: Hi
int: 65
Question 3: What is the output?
class Parent {
void display() { [Link]("Parent"); }
}
class Child extends Parent {
void display() { [Link]("Child"); }
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
[Link]();
}
}
Answer:
Child
Question 4: What is the output?
public class FinallyTest {
static int test() {
try { return 1; }
finally { [Link]("finally runs"); return 2; }
}
public static void main(String[] args) {
[Link](test());
}
}
Answer:
finally runs
2
Question 5: What is the output?
class Counter {
static int count = 0;
Counter() { count++; }
}
public class Test {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link]([Link]);
}
}
Answer:
3
Question 6: What does this print?
int x = 10; final int y = x; [Link](y);
Answer: 10
Question 7: What does this print?
[Link](10/3); [Link](10.0/3);
Answer: 3 3.3333333333333335
Question 8: What does this print?
String s = null; [Link](s + ' world');
Answer: null world
Question 9: What does this print?
int[] arr={1,2,3}; for(int i:arr) [Link](i+' ');
Answer: 1 2 3
Question 10: What does this print?
[Link](1+2+'3'); [Link](1+'2'+3);
Answer: 33 123 (first: 3+'3'=33, second: 1+'2'=49+3=52 — actually '123' because '2' is char)
Question 11: What does this print?
class A{ static int x=5; } class B extends A{ } [Link](B.x);
Answer: 5
Question 12: What does this print?
int i=0; while(i<3){ [Link](i+' '); i++; }
Answer: 0 1 2
Question 13: What does this print?
try{int x=1/0;}catch(Exception
e){[Link]('caught');}finally{[Link]('finally');}
Answer: caught finally
Question 14: What does this print?
Thread t=[Link](); [Link]([Link]());
Answer: main
Question 15: What does this print?
[Link]([Link]('42')+8);
Answer: 50
Question 16: What does this print?
String s='Hello'; [Link]([Link]()+' '+[Link](1));
Answer: 5 e
Question 17: What does this print?
for(int i=1;i<=3;i++) for(int j=1;j<=i;j++) [Link]('*'); [Link]();
Answer: * — only one println, prints ***\n
Question 18: What does this print?
int x=5; x+=3; x*=2; [Link](x);
Answer: 16
Question 19: What does this print?
[Link](true && false); [Link](true || false);
Answer: false true
Question 20: What does this print?
char c='A'; [Link]((int)c); [Link]((char)(c+1));
Answer: 65 B
SECTION G: FIND THE ERROR QUESTIONS
Identify the error in each code snippet and explain how to fix it:
Error Question 1:
abstract class Animal {
abstract void sound();
}
Animal a = new Animal(); // What is wrong?
Error & Fix: Cannot instantiate an abstract class. Fix: Create a concrete subclass and instantiate that.
Error Question 2:
class Parent {
final void display() {}
}
class Child extends Parent {
void display() {} // Error?
}
Error & Fix: Cannot override a final method. Remove the override or remove final from parent.
Error Question 3:
class Test {
static void greet() {
[Link]("Hello " + [Link]); // Error?
}
}
Error & Fix: Cannot use 'this' in a static method. Remove 'this' or make the method non-static.
Error Question 4:
class Box {
Box() {
[Link]("Box created");
this(10); // Error?
}
Box(int size) {
[Link]("Box size: " + size);
}
}
Error & Fix: this() must be the FIRST statement in constructor, not after another statement.
Error Question 5:
interface Flyable {
int speed = 100;
void fly();
}
class Bird implements Flyable {
void fly() { // Error?
[Link]("Flying");
}
}
Error & Fix: Interface methods are public — the implementing method must be public. Add 'public' to fly().
Error Question 6:
class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
[Link](arr[3]); // Error?
}
}
Error & Fix: ArrayIndexOutOfBoundsException: arr has indices 0,1,2 — index 3 doesn't exist.
Error Question 7:
class Test {
void method() throws IOException {
throw new IOException("file error");
}
public static void main(String[] args) {
method(); // Error?
}
}
Error & Fix: Two errors: (1) Cannot call instance method from static main without object. (2) Checked
IOException not handled — wrap in try-catch or add throws to main.
Error Question 8:
Thread t = new Thread(new Runnable() {
public void run() { [Link]("Running"); }
});
[Link](); // What is wrong conceptually?
Error & Fix: [Link]() calls run() in the current thread — no new thread is created! Use [Link]() for
multithreading.
Error Question 9:
class Test {
public static void main(String[] args) {
Thread t = new Thread(() -> [Link]("Lambda thread"));
[Link]();
[Link](); // Error?
}
}
Error & Fix: IllegalThreadStateException: A thread cannot be started more than once.
Error Question 10:
class A {
int x = 5;
}
class B extends A {
int x = 10; // Hides A's x
}
public class Test {
public static void main(String[] args) {
A obj = new B();
[Link](obj.x); // Prints 5 or 10?
}
}
Error & Fix: Fields are NOT polymorphic! obj.x accesses A's x = 5 (field hiding, not overriding). This is a
common conceptual mistake.
Error Question 11:
public class Test {
final int x;
void display() {
[Link](x); // Error?
}
}
Error & Fix: final instance variable x is not initialized. Must initialize at declaration or in constructor.
Error Question 12:
class Student {
private int age;
public int getAge() { return age; }
public void setAge(int age) { age = age; } // Bug?
}
Error & Fix: age = age assigns parameter to itself! Should be [Link] = age to assign to instance variable.
Error Question 13:
import [Link];
public class InputTest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
String s = [Link](); // Bug?
[Link](s);
}
}
Error & Fix: nextInt() leaves newline in buffer. nextLine() reads that empty newline. Fix: add [Link]()
after nextInt() to flush buffer.
Error Question 14:
try {
int x = 10/0;
} catch (Exception e) {
[Link]("General exception");
} catch (ArithmeticException e) { // Error?
[Link]("Arithmetic exception");
}
Error & Fix: Unreachable catch block. ArithmeticException is a subclass of Exception. More specific catches
must come FIRST.
Error Question 15:
class MyException extends Exception {
MyException() { super(); }
}
public class Test {
public static void main(String[] args) {
throw MyException(); // Error?
}
}
Error & Fix: Two errors: (1) Missing 'new' keyword: throw new MyException(); (2) Checked exception not
handled — add try-catch or throws declaration to main.
Error Question 16:
interface A {
default void greet() { [Link]("A"); }
}
interface B {
default void greet() { [Link]("B"); }
}
class C implements A, B {
// No override - Error?
}
Error & Fix: Compile error: C inherits two default implementations of greet(). C must override greet() to
resolve the ambiguity.
Error Question 17:
class Parent {
Parent(int x) {
[Link]("Parent: " + x);
}
}
class Child extends Parent {
Child() {
[Link]("Child"); // Error?
}
}
Error & Fix: Compile error: Parent has no default constructor (only parameterized). Child constructor must
call super(someInt) explicitly.
Error Question 18:
class Test {
static int count;
void increment() { count++; }
static void show() { [Link]("Count: " + count); }
public static void main(String[] args) {
increment(); // Error?
show();
}
}
Error & Fix: Cannot call non-static method increment() from static method main directly. Need to create
object: new Test().increment();
Error Question 19:
public class ThreadTest {
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
[Link]("Thread running");
}
};
[Link]();
[Link](); // Error?
}
}
Error & Fix: join() throws checked InterruptedException. Must handle it: [Link]() must be in try-catch or main
must declare throws InterruptedException.
Error Question 20:
class X implements Runnable {
public void Run() { // Error?
[Link]("Running");
}
}
Error & Fix: Method name is Run() (capital R) but Runnable requires run() (lowercase r). This doesn't
implement run() — class X is technically abstract and causes compile error.
SECTION H: DIFFERENCE-BETWEEN QUESTIONS
Difference: Overloading vs Overriding
Type Overloading Overriding
Class Same class Parent + Child class
Parameters Must differ Must be same
Resolution Compile time Runtime
Polymorphism Compile-time Runtime
Inheritance Not required Required
Difference: Abstract Class vs Interface
Feature Abstract Class Interface
Constructor Yes No
Fields Any type public static final only
Methods Abstract + Concrete Abstract (default/static Java 8+)
Inheritance Single (extends) Multiple (implements)
Access modifier Any public abstract by default
Difference: throw vs throws
Feature throw throws
Purpose Throws exception object Declares possible exceptions
Location Inside method body Method signature
Followed by Exception object Exception class name(s)
Keyword type Statement Clause
Difference: sleep() vs join()
Feature sleep() join()
Purpose Pause current thread Wait for another thread to finish
Static? Yes No
Argument Milliseconds (required) Milliseconds (optional)
Lock release No N/A
Called on Thread class Thread object
Difference: extends Thread vs implements Runnable
Feature extends Thread implements Runnable
Inheritance Uses up the single extend slot Free to extend other classes
Coupling Tight Loose
Lambda? No Yes
Reuse One purpose per class Same Runnable → multiple threads
Preferred? Simple cases Almost always preferred
Difference: final vs finally vs finalize
Keyword Type Purpose
final Modifier Constant var / non-overridable method / non-extenda
finally Block Always executes after try-catch for cleanup
finalize() Method (deprecated) Called by GC before object destruction
Difference: Checked vs Unchecked Exception
Feature Checked Unchecked (Runtime)
Checked at Compile time Runtime
Handling Mandatory Optional
Inherits from Exception RuntimeException
Examples IOException, SQLException NPE, ArithmeticException
Difference: this vs super
Feature this super
Refers to Current object Parent class
this() Calls same-class constructor N/A
super() N/A Calls parent constructor
Use in static? No No
Variable access Current class fields Parent class fields
Difference: Process vs Thread
Feature Process Thread
Memory Independent memory space Shared process memory
Creation Heavy (expensive) Lightweight
Communication IPC mechanisms Shared memory
Isolation Complete Within same process
Example Running a .exe Each tab in Chrome
Difference: next() vs nextLine()
Feature next() nextLine()
Reads Single token (to whitespace) Entire line (to newline)
Spaces Stops at spaces Includes spaces
After nextInt() No buffer issue Reads leftover newline bug
Use for Single words Full sentences
APPENDICES
APPENDIX A: FINAL REVISION CHEAT SHEET
OOP Pillars — One Line Each
• Encapsulation: Private fields + public getters/setters = data protection.
• Inheritance: child extends parent → reuse code. Use IS-A relationship.
• Polymorphism: Overloading (compile-time) + Overriding (runtime) = one name many forms.
• Abstraction: Abstract class / Interface = hide HOW, show WHAT.
Keywords Quick Reference
Keyword Remember This
final CONSTANT! Variable=no change, Method=no override, Class=no extend
static BELONGS TO CLASS! Not object. Shared. Callable without object.
finally CLEANUP BLOCK! Always runs. Except [Link]() or JVM crash.
this CURRENT OBJECT! Shadows fix, constructor chain, pass self.
super PARENT! super()=parent constructor (MUST be first), [Link]()=parent method
abstract INCOMPLETE! Cannot instantiate. Must be implemented by subclass.
interface CONTRACT! implements it. public abstract methods. public static final vars.
throws METHOD DECLARES IT! Method signature. "I might throw this."
throw ACTUALLY THROWS IT! Inside method. Needs new keyword.
Thread States Summary
• NEW → start() → RUNNABLE → (CPU assigned) → running → TERMINATED
• sleep() → TIMED_WAITING (time expires → RUNNABLE)
• join() calling thread → WAITING until target terminates
• synchronized block unavailable → BLOCKED
Exception Hierarchy
• Throwable → Error (OutOfMemoryError) + Exception
• Exception → Checked (IOException, SQLException) + Unchecked (RuntimeException)
• RuntimeException → NPE, ArithmeticException, ArrayIndexOutOfBounds, ClassCast
APPENDIX B: COMMON MISTAKES STUDENTS
MAKE
1. Calling run() instead of start()
run() executes in current thread. start() creates NEW thread. Always use start() for multithreading.
2. Not handling InterruptedException from sleep()/join()
Both methods throw checked InterruptedException. Always wrap in try-catch.
3. nextLine() after nextInt() bug
nextInt() leaves '\n' in buffer. Call [Link]() after nextInt() to clear it before reading a line.
4. Trying to instantiate abstract class
new AbstractClass() → compile error! Instantiate a concrete subclass instead.
5. Not implementing all abstract methods
If you miss even one abstract method in a subclass, the subclass must also be abstract.
6. Using this inside static method
static methods have no 'this'. Remove this, or make the method non-static.
7. Confusing throw and throws
throw (inside method) = actually throw. throws (method signature) = declare you might throw.
8. Putting general Exception catch before specific catch
Compile error: unreachable catch. Always put specific exceptions BEFORE general Exception.
9. Not adding public when implementing interface methods
Interface methods are public. Override must be public too.
10. Restarting a terminated thread
IllegalThreadStateException. A thread object can only be started once.
11. Confusing method hiding (static) with overriding
static methods are hidden, not overridden. Polymorphism doesn't apply.
12. Forgetting super() in child constructor when parent has no default constructor
Compile error. If parent only has parameterized constructor, child must call super(args).
13. Variable shadowing without this
setAge(int age) { age = age; } — assigns parameter to itself! Use [Link] = age.
14. Modifying interface constant
Interface variables are final. Cannot assign new value.
15. Confusing final class (can instantiate) with abstract class (cannot)
final class = can create object, cannot extend. abstract = cannot create object directly.
APPENDIX C: LAST NIGHT REVISION NOTES
■ Scan these before you sleep. If you understand all, you are ready!
01. 4 OOP pillars: Encapsulation, Inheritance, Polymorphism, Abstraction
02. Polymorphism: Overloading = compile-time, Overriding = runtime
03. @Override annotation = best practice for overriding
04. Upcasting = implicit (safe). Downcasting = explicit (can fail with
ClassCastException)
05. Dynamic dispatch: actual object type determines which overriding method runs
06. Abstract class: abstract keyword, no instantiation, can have both abstract and
concrete methods
07. Interface: contract, implements, all methods public abstract (Java 7-), public
static final vars
08. Java 8 interfaces: default methods and static methods added
09. Multiple interface implementation = solution to Multiple Inheritance problem
10. If two interfaces have same default method → implementing class MUST override it
11. final variable = constant. final method = no override. final class = no extend
12. static members belong to class. No this in static context.
13. Static block runs ONCE at class load. Instance block runs BEFORE each constructor.
14. Order: Static block → [main starts] → Instance block → Constructor
15. Access modifiers: private < default < protected < public
16. protected = same package + subclasses in any package
17. this = current object. this() = constructor chain. super() = parent constructor
18. super() and this() must be first statement in constructor
19. nextLine() after nextInt() bug — fix with extra [Link]()
20. Scanner is in [Link]. BufferedReader is in [Link]
21. Exception hierarchy: Throwable → Error / Exception → Checked/Unchecked
22. Checked = must handle at compile time. Unchecked = RuntimeException
23. throw = actually throw. throws = declare. finally = always runs (not with
[Link])
24. Custom exception: extend Exception (checked) or RuntimeException (unchecked)
25. Thread states: NEW → RUNNABLE → (BLOCKED/WAITING/TIMED_WAITING) → TERMINATED
26. start() = new thread + calls run(). run() alone = no new thread!
27. sleep() = static, pauses thread, keeps locks, throws InterruptedException
28. join() = instance method, makes caller wait for target thread to finish
29. extends Thread = simpler but uses inheritance slot
30. implements Runnable = preferred, flexible, allows extending other classes,
lambda-ready
31. Thread priority: 1 (MIN) to 10 (MAX), default 5 — doesn't guarantee order
32. isAlive() = true after start(), false before start() or after termination
APPENDIX D: MOST IMPORTANT FOR EXAM ■
These topics appear in almost every exam. Master them!
■ 1. Polymorphism
Overloading vs Overriding comparison table. Dynamic dispatch. Why overriding is runtime.
■ 2. Abstract vs Interface
When to use each. Interface for contract, abstract for partial implementation.
■ 3. final vs finally vs finalize
Always compared in exams. Know exact purpose and differences.
■ 4. static keyword
Why main() is static. Static method limitations. Counter using static.
■ 5. this keyword
Variable shadowing fix. this() constructor chaining rule (must be first).
■ 6. Static/Instance block order
Execution order question is very common: static → instance → constructor
■ 7. Access Modifiers Table
Know the 4-column table: same class, same pkg, subclass, other pkg
■ 8. Exception Handling
try-catch-finally, throw vs throws, checked vs unchecked, custom exception
■ 9. Thread start() vs run()
Most common multithreading exam question. Know WHY start() is correct.
■ 10. join() purpose and example
Know what happens with and without join(). Output tracing question.
■ 11. Runnable vs Thread
Why Runnable is preferred. Lambda with Runnable.
■ 12. nextLine() bug
Classic Scanner bug — know the cause and fix.
■ 13. Pattern printing
Pyramid and hollow square are most commonly asked.
■ 14. super keyword
super() constructor call must be first. [Link]() vs [Link].
■ 15. Diamond Problem solution
Multiple interface inheritance and conflict resolution override.
END OF GUIDE
Complete Java OOP & Multithreading Final Exam Guide
Author: NAHIN UR ROSHID DURJOY — 2025 Edition