Java Interview Playbook


1️⃣ OOPs (Object Oriented Programming)


1. What are the 4 Pillars of OOP?

  • Encapsulation

  • Abstraction

  • Inheritance

  • Polymorphism

Example Combining All

abstract class Animal { // Abstraction
abstract void sound();
}

class Dog extends Animal { // Inheritance
private String name; // Encapsulation

Dog(String name) {
this.name = name;
}

@Override
void sound() { // Runtime Polymorphism
System.out.println("Dog barks");
}
}

🔹 Encapsulation

2. What is Encapsulation?

  • Binding data + methods together

  • Hide variables using private

  • Access via getters/setters

  • Provides data security and validation

Example

class Employee {
private int salary; // hidden

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
if (salary > 0) {
this.salary = salary;
}
}
}

Why needed:

  • Protect data

  • Add validation

  • Improve maintainability


🔹 Abstraction

3. What is Abstraction?

  • Hides implementation details

  • Shows only essential behavior

  • Achieved using:

    • Abstract class

    • Interface


Using Abstract Class

abstract class Payment {
abstract void pay(double amount);
}

class UpiPayment extends Payment {
void pay(double amount) {
System.out.println("Paid via UPI: " + amount);
}
}

Using Interface

interface Shape {
double area();
}

class Circle implements Shape {
double radius;

Circle(double radius) {
this.radius = radius;
}

public double area() {
return Math.PI * radius * radius;
}
}

4. Abstract Class vs Interface

Abstract Class

  • Can have abstract + concrete methods

  • Can maintain state

  • Has constructor

  • Supports single inheritance

  • Used for closely related classes

Interface

  • Defines contract

  • Provides full abstraction

  • Supports multiple inheritance

  • No constructor

  • Used for capability across unrelated classes


Example

abstract class Vehicle {
abstract void start();

void fuelType() {
System.out.println("Petrol/Diesel");
}
}

interface Electric {
void charge();
}

class Tesla extends Vehicle implements Electric {

void start() {
System.out.println("Start with button");
}

public void charge() {
System.out.println("Charging...");
}
}

🔹 Inheritance

5. What is Inheritance?

  • IS-A relationship

  • Child inherits parent properties

  • Uses extends keyword

Example

class Animal {
void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}

Usage:

Dog d = new Dog();
d.eat(); // inherited
d.bark();

🔹 Polymorphism

6. What is Polymorphism?

1. Compile-Time Polymorphism (Method Overloading)

  • Same method name

  • Different parameter list

  • Resolved at compile time

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}
}

2. Runtime Polymorphism (Method Overriding)

  • Same method name

  • Same parameters

  • Resolved at runtime

  • Achieved using inheritance

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

Animal a = new Dog();
a.sound(); // Dog barks

7. Method Overriding (Rules + Example)

Rules:

  • Same method name

  • Same parameters

  • Same return type (covariant allowed)

  • Cannot override static, final, private methods

class Parent {
void show() {
System.out.println("Parent");
}
}

class Child extends Parent {
@Override
void show() {
System.out.println("Child");
}
}

8. Method Overloading (Rules + Example)

Rules:

  • Same method name

  • Different parameter list

  • Happens at compile time

class Printer {
void print(String s) {
System.out.println(s);
}

void print(int n) {
System.out.println(n);
}
}

🔹 Constructor Concepts

9. Constructor Chaining

  • Using this() → calls current class constructor

  • Using super() → calls parent constructor

Example using this()

class Person {
String name;
int age;

Person() {
this("Unknown", 0);
}

Person(String name, int age) {
this.name = name;
this.age = age;
}
}

Example using super()

class Animal {
Animal(String type) {
System.out.println(type);
}
}

class Dog extends Animal {
Dog() {
super("Mammal");
}
}

🔹 super Keyword

10. What is super?

Used to:

  • Call parent constructor

  • Call parent method

  • Access parent variable

class Parent {
int x = 10;

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

class Child extends Parent {
int x = 20;

void show() {
System.out.println(super.x);
super.display();
}
}

🔹 this Keyword

11. What is this?

  • Refers to current object

Used to:

  • Differentiate instance variable

  • Call another constructor

  • Pass current object

Example 1: Variable Differentiation

class Student {
String name;

Student(String name) {
this.name = name;
}
}

Example 2: Constructor Call

class Test {
Test() {
this(10);
}

Test(int x) {
System.out.println(x);
}
}

Example 3: Passing Current Object

class Demo {
void display(Demo obj) {
System.out.println("Method called");
}

void show() {
display(this);
}
}

🔹 Composition vs Inheritance

12. Difference Composition vs Inheritance

Inheritance → IS-A

class Animal {}
class Dog extends Animal {}

Composition → HAS-A

class Engine {}

class Car {
private Engine engine = new Engine();
}

Prefer composition over inheritance for flexibility.


🔹 Object Class

13. What is Object class?

  • Root class of Java

  • Every class extends Object

Common methods:

  • toString()

  • equals()

  • hashCode()

  • clone()

  • wait()

  • notify()

Example:

String s = "Hello";
System.out.println(s.toString());
System.out.println(s.hashCode());

🔹 equals() and hashCode()

14. Why Override?

  • Required for HashMap / HashSet

  • Equal objects must have same hashCode

class Employee {
int id;

Employee(int id) {
this.id = id;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return id == e.id;
}

@Override
public int hashCode() {
return Integer.hashCode(id);
}
}

🔹 Immutable Class

15. What is Immutable Class?

  • Object state cannot change after creation

  • Class must be final

  • Fields private and final

  • No setters

final class Person {
private final String name;

Person(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

Example: String class is immutable.

16. What is Multiple Inheritance and how does Java handle it?

Answer:

Multiple inheritance means a class inheriting from more than one class.

Java does NOT support multiple inheritance with classes to avoid the Diamond Problem.

Diamond Problem:

class A
class B extends A
class C extends A
class D extends B, C // Ambiguity

If both B and C override a method from A, D will not know which version to use.

How Java Solves It:

Java supports multiple inheritance using interfaces.

interface A {
default void show() {
System.out.println("A");
}
}

interface B {
default void show() {
System.out.println("B");
}
}

class C implements A, B {
public void show() {
A.super.show(); // Must override and resolve conflict
}
}

17. Difference between Abstraction and Encapsulation

AbstractionEncapsulation
Hides implementationHides data
Achieved via interface/abstract classAchieved via private variables
Focus on whatFocus on how
Design-level conceptImplementation-level concept

Example:

abstract class Payment {
abstract void pay();
}

class CardPayment extends Payment {
void pay() {
System.out.println("Paid by card");
}
}

Encapsulation example:

class User {
private String password;

public void setPassword(String password) {
this.password = password;
}
}

18. What is IS-A vs HAS-A Relationship?

IS-A → Inheritance
HAS-A → Composition

IS-A Example:

class Animal {}
class Dog extends Animal {}

HAS-A Example:

class Engine {}

class Car {
private Engine engine = new Engine();
}

Prefer HAS-A for flexibility.



2️⃣ Java Basics 


1. What are the main features of Java?

Answer:

Java provides:

  • Platform Independent (Write Once Run Anywhere)

  • Object Oriented

  • Robust (Strong memory management, exception handling)

  • Secure

  • Multithreaded

  • High Performance (JIT compiler)

  • Distributed

  • Dynamic

Java achieves platform independence using bytecode and the JVM.


2. What is JVM, JRE, and JDK?

Answer:

JVM (Java Virtual Machine)

  • Executes Java bytecode

  • Platform dependent implementation

JRE (Java Runtime Environment)

  • JVM + Libraries

  • Used to run Java applications

JDK (Java Development Kit)

  • JRE + Development tools (javac, debugger, javadoc)

  • Used to develop Java applications


3. How Java is platform independent?

Answer:

  • Java source code (.java) is compiled into bytecode (.class).

  • Bytecode runs on JVM.

  • JVM is available for different OS.

  • Same bytecode runs on any OS having JVM.

Flow:

.java → javac → .class (bytecode) → JVM → OS


4. What is the difference between JIT and JVM?

Answer:

JVM

  • Executes bytecode

  • Provides runtime environment

JIT (Just In Time Compiler)

  • Part of JVM

  • Converts bytecode into native machine code at runtime

  • Improves performance


5. What are primitive data types in Java?

Answer:

Java has 8 primitive types:

TypeSizeExample
byte1 bytebyte b = 10;
short2 bytesshort s = 100;
int4 bytesint a = 1000;
long8 byteslong l = 10000L;
float4 bytesfloat f = 10.5f;
double8 bytesdouble d = 10.5;
char2 byteschar c = 'A';
boolean1 bit (logical)boolean flag = true;

6. What is the default value of variables?

Answer:

Default values are given only to instance variables, not local variables.

TypeDefault Value
int0
long0L
float0.0f
double0.0d
booleanfalse
char'\u0000'
Objectnull

7. What is the difference between instance variable and local variable?

Answer:

Instance Variable

  • Declared inside class but outside method

  • Stored in heap

  • Gets default value

Local Variable

  • Declared inside method

  • Stored in stack

  • No default value (must initialize)

Example:

class Test {
int x; // instance variable

void method() {
int y = 10; // local variable
}
}

8. What is type casting in Java?

Answer:

Type casting means converting one data type to another.

1. Widening (Implicit)

Smaller → Larger type

int a = 10;
double d = a; // automatic

2. Narrowing (Explicit)

Larger → Smaller type

double d = 10.5;
int a = (int) d; // explicit casting

9. What is the difference between == and equals()?

Answer:

==

  • Compares memory reference (for objects)

  • Compares value (for primitives)

equals()

  • Compares content

  • Defined inside Object class

  • Can be overridden

Example:

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true

10. What is a wrapper class?

Answer:

Wrapper classes convert primitive data types into objects.

PrimitiveWrapper
intInteger
longLong
doubleDouble
charCharacter
booleanBoolean

Example:

int a = 10;
Integer obj = Integer.valueOf(a); // Boxing
int b = obj; // Unboxing

11. What is autoboxing and unboxing?

Answer:

Autoboxing
Automatic conversion of primitive to wrapper.

Integer i = 10;

Unboxing
Wrapper to primitive automatically.

int x = i;

12. What is the difference between pass by value and pass by reference in Java?

Answer:

Java is strictly pass by value only.

  • Primitive → value copied

  • Object → reference copied (not object)

Example:

class Test {
int x = 10;
}

public class Main {
public static void main(String[] args) {
Test t = new Test();
modify(t);
System.out.println(t.x); // 20
}

static void modify(Test t) {
t.x = 20;
}
}

The reference is copied, but both point to same object.


13. What is a static keyword?

Answer:

Static belongs to class, not object.

Can be used with:

  • Variable

  • Method

  • Block

  • Nested class

Example:

class Test {
static int count = 0;

static void display() {
System.out.println("Static method");
}
}

Static members are loaded once when class loads.

14. What is Platform Independence?

Java code is compiled into bytecode.

Bytecode runs on JVM.

Same .class file runs on any OS with JVM.

Flow:

.java → javac → .class → JVM → OS

15. What is WORA?

WORA = Write Once Run Anywhere.

Means:

Compile once
Run on any system with JVM


16. Memory allocation for primitive vs object?

Primitive:

  • Stored in stack (if local variable)

  • Direct value stored

Object:

  • Reference stored in stack

  • Object stored in heap

Example:

int x = 10; // stack
String s = "Java"; // reference in stack, object in heap

17. What is default value of static variables?

Static variables:

  • Stored in Method Area (Metaspace)

  • Get default value same as instance variables

Example:

class Test {
static int x;
}

System.out.println(Test.x); // 0



3️⃣ Java Keywords


1. What are Java keywords?

Answer:

Java keywords are reserved words that have predefined meaning in Java.
They cannot be used as variable names, class names, or method names.

Example:

  • class

  • public

  • static

  • final

  • return

  • try

  • catch


2. What is the difference between final, finally, and finalize?

Answer:

final

Used with:

  • Variable → value cannot change

  • Method → cannot be overridden

  • Class → cannot be inherited

final int x = 10;
// x = 20; // Compilation error

finally

  • Used in try-catch block

  • Always executes (except JVM crash)

try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Exception");
} finally {
System.out.println("Always executes");
}

finalize

  • Method of Object class

  • Called by Garbage Collector before destroying object

  • Deprecated in modern Java (not recommended)


3. What is the difference between static and non-static?

static

  • Belongs to class

  • Loaded once when class loads

  • Can access only static members directly

Non-static

  • Belongs to object

  • Requires object creation

Example:

class Test {
static int a = 10;
int b = 20;
}

4. What is the use of this keyword?

Answer:

this refers to current object.

Used to:

  • Differentiate instance variable and local variable

  • Call current class constructor

  • Pass current object

Example:

class Test {
int x;

Test(int x) {
this.x = x; // differentiate
}
}

5. What is the use of super keyword?

Answer:

super refers to parent class object.

Used to:

  • Access parent class variable

  • Call parent class method

  • Call parent constructor

Example:

class Parent {
int x = 10;
}

class Child extends Parent {
void display() {
System.out.println(super.x);
}
}

6. What is the use of volatile keyword?

Answer:

volatile ensures visibility of variable changes across threads.

  • Stored in main memory

  • Prevents thread caching issues

  • Used in multithreading

Example:

class Test {
volatile boolean flag = true;
}

7. What is transient keyword?

Answer:

transient prevents variable from being serialized.

Used in serialization.

class User implements Serializable {
String name;
transient String password;
}

password will not be saved during serialization.


8. What is synchronized keyword?

Answer:

synchronized is used to control multithreading access.

  • Only one thread can access synchronized block/method at a time.

Example:

class Counter {
int count = 0;

synchronized void increment() {
count++;
}
}

9. What is abstract keyword?

Answer:

abstract is used with:

  • Class → cannot be instantiated

  • Method → no implementation

Example:

abstract class Animal {
abstract void sound();
}

10. What is native keyword?

Answer:

native indicates method is implemented in another language (usually C/C++).

Used with JNI (Java Native Interface).

Example:

public native void show();

11. What is strictfp keyword?

Answer:

strictfp ensures floating-point calculations follow IEEE 754 standard consistently across platforms.

Example:

public strictfp class Test {
}

Rarely used in modern development.


12. What is instanceof keyword?

Answer:

instanceof checks whether object belongs to a class.

Example:

String s = "Java";

if (s instanceof String) {
System.out.println("Yes");
}

13. What is the difference between break and continue?

break

  • Terminates loop

continue

  • Skips current iteration

Example:

for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
if (i == 4) break;
System.out.println(i);
}

Output:
1
2


14. What is the difference between throw and throws?

throw

  • Used to explicitly throw exception

throw new RuntimeException("Error");

throws

  • Declares exception in method signature

void test() throws IOException {
}

15. Can we use return inside finally block?

Answer:

Yes, but not recommended.

If return is used in finally, it overrides previous return values and suppresses exceptions.

Bad practice example:

int test() {
try {
return 1;
} finally {
return 2; // overrides
}
}

16. What is enum?

enum defines fixed set of constants.

enum Day {
MONDAY, TUESDAY, WEDNESDAY
}

Can contain methods and constructors.


17. What is assert?

Used for debugging.

int age = 10;
assert age > 18 : "Invalid age";

Enabled using:

java -ea Test

18. What is var (Java 10)?

Local variable type inference.

var name = "Java";
var number = 10;

Compiler infers type.

Restrictions:

  • Only local variables

  • Cannot be null without type



4️⃣ Strings – String, StringBuilder, StringBuffer


1. What is String in Java?

Answer:

String is a class in java.lang package.

  • Immutable

  • Sequence of characters

  • Stored in String Constant Pool

  • Overrides equals() and hashCode()

Example:

String s = "Java";

2. Why is String immutable in Java?

Answer:

String is immutable for:

  • Security (URL, DB credentials cannot change)

  • String pool optimization

  • Thread safety

  • Caching of hashcode

  • Used in class loading

Example:

String s = "Java";
s.concat(" World");

System.out.println(s); // Output: Java

New object is created, original is unchanged.


3. What is String Constant Pool?

Answer:

String Constant Pool is a special memory area inside Heap.

  • Stores string literals

  • Avoids duplicate objects

  • Improves memory efficiency

Example:

String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2); // true

Both refer to same pool object.


4. Difference between String literal and new String()

Answer:

String Literal

String s1 = "Java";
  • Stored in String Pool

  • Reuses existing object


new String()

String s2 = new String("Java");
  • Creates object in Heap

  • Always creates new object

Comparison:

String s1 = "Java";
String s2 = new String("Java");

System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true

5. Difference between == and equals() in String?

==

  • Compares memory reference

equals()

  • Compares content

Example:

String a = "Hello";
String b = new String("Hello");

System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

6. What is intern() method?

Answer:

intern() moves string into String Constant Pool (if not present).

Example:

String s1 = new String("Java");
String s2 = s1.intern();

String s3 = "Java";

System.out.println(s2 == s3); // true

7. What is StringBuilder?

Answer:

StringBuilder is:

  • Mutable

  • Not thread-safe

  • Faster than StringBuffer

  • Introduced in Java 5

Used for string modification in single-threaded environment.

Example:

StringBuilder sb = new StringBuilder("Java");
sb.append(" World");

System.out.println(sb); // Java World

8. What is StringBuffer?

Answer:

StringBuffer is:

  • Mutable

  • Thread-safe

  • Synchronized

  • Slower than StringBuilder

Used in multi-threaded environment.

Example:

StringBuffer sb = new StringBuffer("Java");
sb.append(" World");

System.out.println(sb);

9. Difference between String, StringBuilder, and StringBuffer

FeatureStringStringBuilderStringBuffer
MutableNoYesYes
Thread SafeYesNoYes
PerformanceSlowFastSlower than Builder
IntroducedJava 1.0Java 5Java 1.0

Interview one-line answer:

  • Use String for fixed text

  • Use StringBuilder for single-thread modification

  • Use StringBuffer for multi-thread modification


10. Why StringBuilder is faster than StringBuffer?

Answer:

StringBuffer methods are synchronized.

Synchronization adds overhead.

StringBuilder methods are not synchronized, so faster.


11. What happens when we concatenate strings using + operator?

Answer:

Compiler internally converts:

String s = "Java" + "World";

Into:

String s = new StringBuilder()
.append("Java")
.append("World")
.toString();

For multiple concatenations in loop, performance degrades.

Bad practice:

String s = "";
for(int i=0; i<1000; i++){
s += i;
}

Better:

StringBuilder sb = new StringBuilder();
for(int i=0; i<1000; i++){
sb.append(i);
}

12. Can we make String mutable?

Answer:

No.

String class is final and immutable.

To modify string, use:

  • StringBuilder

  • StringBuffer


13. How many objects are created here?

String s = new String("Java");

Answer:

Two objects:

  1. "Java" in String Pool

  2. new String object in Heap


14. What is difference between length() and capacity()?

For String:

  • length() returns number of characters

For StringBuilder / StringBuffer:

  • length() → current character count

  • capacity() → total allocated memory

Example:

StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.length()); // 4
System.out.println(sb.capacity()); // 20 (default 16 + length)

15. Why is String class final?

Answer:

String is final to:

  • Prevent modification

  • Ensure immutability

  • Maintain security

  • Avoid subclass altering behavior


16. Why is String used as key in HashMap?

Because:

  • Immutable

  • hashCode cached

  • Thread-safe

  • Reliable for hashing

If mutable key changes → hash bucket changes → retrieval fails.


17. How does String hashCode work internally?

Implementation:

public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
for (char c : value) {
h = 31 * h + c;
}
hash = h;
}
return h;
}

Formula:

s[0]*31^(n-1) + s[1]*31^(n-2) + ...

Hash is cached after first calculation.



5️⃣ Exception Handling


1. What is an Exception in Java?

Answer:

An Exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program.

Examples:

  • Divide by zero

  • NullPointerException

  • File not found


2. What is the difference between Error and Exception?

Exception

  • Can be handled

  • Occurs due to application issues

  • Example: NullPointerException, IOException

Error

  • Cannot be handled normally

  • Occurs due to JVM issues

  • Example: OutOfMemoryError, StackOverflowError

Interview one-line answer:
Exceptions are recoverable, Errors are not.


3. What is the hierarchy of Exception classes?

Answer:

Top class:
Object
→ Throwable
→ Exception
→ Error

Exception further divided into:

  • Checked Exception

  • Unchecked Exception (RuntimeException)


4. What is the difference between Checked and Unchecked Exception?

Checked Exception

  • Checked at compile time

  • Must handle using try-catch or declare using throws

  • Compilation error if not handled

  • Usually caused by external conditions (file, DB, network)

  • Not typically a programmer mistake

  • Subclass of Exception (but not RuntimeException)

Examples: IOException, SQLException

void readFile() throws IOException {
}

Unchecked Exception

  • Occurs at runtime

  • Not mandatory to handle

  • Subclass of RuntimeException

  • Mostly caused by programmer mistakes

  • Indicates logical or coding errors

  • Program compiles successfully but fails at runtime

Examples: NullPointerException, ArithmeticException

int a = 10 / 0// ArithmeticException


Key Interview Difference

Checked → Compile-time, mandatory handling, external issues
Unchecked → Runtime, optional handling, programmer mistakes


5. What is try-catch block?

Answer:

Used to handle exceptions.

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}

6. Can we have multiple catch blocks?

Answer:

Yes.

Order must be from specific to general.

Correct:

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic");
} catch (Exception e) {
System.out.println("General");
}

Wrong (Compilation error):

catch (Exception e)
catch (ArithmeticException e)

7. What is finally block?

Answer:

finally block always executes (except JVM crash or System.exit).

Used for:

  • Closing resources

  • Cleaning up code

try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Cleanup");
}

8. What is throw vs throws?

throw

Used to explicitly throw exception.

throw new RuntimeException("Error");

throws

Declares exception in method signature.

void test() throws IOException {
}

9. What is the difference between final, finally, and finalize?

final

Constant variable / method cannot override / class cannot extend

finally

Block used in exception handling

finalize

Method called before garbage collection
Deprecated and not recommended


10. What is try-with-resources?

Answer:

Introduced in Java 7.

Automatically closes resources.

Resource must implement AutoCloseable.

Example:

try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}

No need for finally block.


11. What is custom exception?

Answer:

User-defined exception created by extending Exception or RuntimeException.

Checked custom exception:

class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}

Usage:

if(age < 18) {
throw new InvalidAgeException("Not eligible");
}

12. What happens if exception is not handled?

Answer:

  • JVM handles it

  • Prints stack trace

  • Terminates program


13. What is stack trace?

Answer:

Stack trace shows:

  • Exception type

  • Message

  • Method call hierarchy

  • Line number where exception occurred

Example:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(Test.java:5)

14. Can we write multiple exceptions in single catch block?

Answer:

Yes. From Java 7 (Multi-catch).

try {
// code
} catch (IOException | SQLException e) {
e.printStackTrace();
}

15. What is difference between printStackTrace(), getMessage(), and toString()?

printStackTrace()

Prints full stack trace.

getMessage()

Returns exception message.

toString()

Returns exception class + message.

Example:

catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}

16. Can we have try without catch?

Answer:

Yes, if finally is present.

try {
System.out.println("Try block");
} finally {
System.out.println("Finally block");
}

But try alone without catch or finally is not allowed.


17. What is exception propagation?

Answer:

If exception is not handled in method, it propagates to caller method.

Example:

void method1() {
method2();
}

void method2() {
int a = 10 / 0;
}

Exception propagates to method1, then to JVM.


18. What is Exception Chaining?

Wrapping one exception inside another.

try {
int a = 10 / 0;
} catch (Exception e) {
throw new RuntimeException("Wrapped", e);
}

Helps track root cause.


19. Execution order of try-catch-finally

Order:

  1. try

  2. catch (if exception)

  3. finally (always except JVM crash/System.exit)


20. Can finally block skip execution?

Yes, if:

System.exit(0);

JVM terminates immediately.



6️⃣ Collections


1. What is Java Collection Framework?

Answer:

Java Collection Framework is a set of interfaces and classes used to store and manipulate groups of objects dynamically.

It provides:

  • Ready-made data structures

  • Dynamic resizing

  • Searching and sorting utilities

  • Better performance than arrays

  • Standard APIs for data handling

Main Interfaces:

  • List

  • Set

  • Queue

  • Map (Not a child of Collection, but part of framework)


🔹 List Implementations


2. What is ArrayList?

  • Dynamic array implementation

  • Allows duplicates

  • Maintains insertion order

  • Allows multiple null values

  • Fast random access O(1)

  • Slow insert/delete in middle O(n)

  • Not thread-safe

  • Fail-Fast iterator

Example:

List<String> list = new ArrayList<>();
list.add("Java");
list.add("Spring");

3. What is LinkedList?

  • Doubly linked list

  • Allows duplicates

  • Maintains order

  • Slow random access O(n)

  • Fast insert/delete O(1)

  • Not thread-safe

  • Fail-Fast

List<String> list = new LinkedList<>();

4. What is CopyOnWriteArrayList?

  • Thread-safe

  • Creates new copy on every write

  • Fail-Safe iterator

  • Good for read-heavy systems

  • Slow for frequent writes

List<String> list = new CopyOnWriteArrayList<>();

5. What is synchronizedList?

  • Thread-safe wrapper

  • Provided by Collections class

  • Manual synchronization needed during iteration

List<String> list =
Collections.synchronizedList(new ArrayList<>());

🔹 Set Implementations


6. What is HashSet?

  • No duplicates

  • No guaranteed order

  • Allows one null

  • Backed by HashMap

  • Fail-Fast

Set<String> set = new HashSet<>();

7. What is LinkedHashSet?

  • No duplicates

  • Maintains insertion order

  • Slightly slower than HashSet

Set<String> set = new LinkedHashSet<>();

8. What is TreeSet?

  • No duplicates

  • Sorted order

  • No null allowed

  • O(log n)

  • Uses Red-Black Tree

Set<Integer> set = new TreeSet<>();

🔹 Map Implementations


9. What is HashMap?

  • Key-value pairs

  • Unique keys

  • One null key allowed

  • Not thread-safe

  • O(1) average

  • Fail-Fast

Map<Integer, String> map = new HashMap<>();

10. What is LinkedHashMap?

  • Maintains insertion order

  • Can maintain access order (LRU use case)

Map<Integer, String> map = new LinkedHashMap<>();

11. What is TreeMap?

  • Sorted keys

  • No null key

  • O(log n)

  • Uses Red-Black Tree

Map<Integer, String> map = new TreeMap<>();

12. What is ConcurrentHashMap?

  • Thread-safe

  • High concurrency

  • No null key or value

  • Fail-Safe iterator

  • Better than Hashtable

ConcurrentHashMap<String, Integer> map =
new ConcurrentHashMap<>();

🔹 Fail-Fast vs Fail-Safe


13. What is Fail-Fast?

  • Throws ConcurrentModificationException

  • Works on original collection

  • Used in ArrayList, HashSet, HashMap

for (String s : list) {
list.add("New"); // Exception
}

14. What is Fail-Safe?

  • No exception during modification

  • Works on copy

  • Used in ConcurrentHashMap, CopyOnWriteArrayList

CopyOnWriteArrayList<String> list =
new CopyOnWriteArrayList<>();

🔹 Immutable and Unmodifiable Collections


15. What is unmodifiableList?

  • Read-only view

  • Original list can still change

  • Throws UnsupportedOperationException on modify

List<String> roles = new ArrayList<>();
List<String> unmodifiable =
Collections.unmodifiableList(roles);

16. How to create Immutable List?

Java 9+

List<String> list = List.of("Java", "Spring");
  • Completely immutable

  • No modification allowed

Using Arrays.asList()

List<String> list =
Arrays.asList("Java", "Spring");
  • Fixed size

  • Cannot add/remove

  • Can modify existing elements

17. Difference between HashMap and Hashtable

HashMapHashtable
Not thread-safeThread-safe
Allows one null keyNo null key
FasterSlower
Introduced in Java 1.2Java 1.0

18. What happens when two keys have same hash?

Collision occurs.

Before Java 8:
LinkedList used.

After Java 8:
If bucket size > 8 → converted to Red-Black Tree (Treeify).


19. How HashMap resizing works internally?

Default load factor = 0.75

Threshold = capacity × loadFactor

When size exceeds threshold:

  • Capacity doubles

  • Rehash occurs

  • Elements redistributed


20. Comparable vs Comparator

Comparable:

  • Defines natural ordering

  • Implemented in class

class Student implements Comparable<Student> {
public int compareTo(Student s) {
return this.id - s.id;
}
}

Comparator:

  • External sorting logic

Collections.sort(list, (a, b) -> a.name.compareTo(b.name));

21. What is BlockingQueue?

Part of java.util.concurrent.

Thread-safe queue.

Blocks when:

  • Queue empty (take)

  • Queue full (put)

Example:

BlockingQueue<Integer> queue =
new ArrayBlockingQueue<>(5);

Used in Producer-Consumer.


🔹 Quick Comparison Table

CollectionDuplicatesOrderThread-SafeNull Allowed
ArrayListYesYesNoYes
LinkedListYesYesNoYes
HashSetNoNoNoOne null
TreeSetNoSortedNoNo
HashMapKey uniqueNoNoOne null key
TreeMapKey uniqueSortedNoNo
ConcurrentHashMapKey uniqueNoYesNo

🔹 Frequently Asked Interview Questions

  • Difference between HashMap and ConcurrentHashMap

  • How HashMap works internally

  • What is load factor (default 0.75)

  • What happens during rehashing

  • Difference between unmodifiable and immutable

  • When to use ArrayList vs LinkedList

  • Why TreeSet does not allow null


🔹 Strong Interview Closing Line

Always choose collection based on:

  • Need duplicates?

  • Need ordering or sorting?

  • Need thread safety?

  • Read-heavy or write-heavy?

  • Performance requirement?



7️⃣ Generics 


1. What are Generics in Java?

Generics allow classes, interfaces, and methods to operate on types specified at compile time.

They provide:

  • Type safety

  • Compile-time checking

  • Elimination of type casting

  • Code reusability

Example without Generics:

List list = new ArrayList();
list.add("Java");
String s = (String) list.get(0); // Casting required

Example with Generics:

List<String> list = new ArrayList<>();
list.add("Java");
String s = list.get(0); // No casting needed

2. Why do we need Generics?

  • To avoid ClassCastException

  • To ensure compile-time type checking

  • To improve readability

  • To remove explicit casting

Interview Line:
Generics provide compile-time type safety.


3. How to create a Generic Class?

class Box<T> {
private T value;

public void set(T value) {
this.value = value;
}

public T get() {
return value;
}
}

Usage:

Box<String> box = new Box<>();
box.set("Java");
System.out.println(box.get());

4. How to create a Generic Method?

public class Test {
public static <T> void print(T value) {
System.out.println(value);
}
}

Usage:

print("Java");
print(100);

5. What is Bounded Type Parameter?

Restricts the types that can be used.

Example:

class NumberBox<T extends Number> {
T value;
}

Only subclasses of Number allowed.


6. What are Wildcards in Generics?

Wildcards are represented by ?.

Used when type is unknown.


a) Unbounded Wildcard

List<?> list;

Accepts any type.


b) Upper Bounded Wildcard

List<? extends Number> list;

Accepts Number and its subclasses.

Used for reading data.


c) Lower Bounded Wildcard

List<? super Integer> list;

Accepts Integer and its parent classes.

Used for writing data.


7. What is PECS Principle?

PECS = Producer Extends, Consumer Super

  • If a collection produces data → use extends

  • If a collection consumes data → use super

Example:

void print(List<? extends Number> list) { }
void add(List<? super Integer> list) { }

8. What is Type Erasure?

Java removes generic type information at runtime.

Generics exist only at compile time.

Example:

List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();

At runtime both are just ArrayList.


9. Can we create Generic Arrays?

No.

This is illegal:

T[] arr = new T[10]; // Compilation error

Because of type erasure.


10. Can we use Primitive Types in Generics?

No.

Wrong:

List<int> list; // Not allowed

Correct:

List<Integer> list;

Generics work only with objects.


11. What is Raw Type?

Using generic class without specifying type.

Example:

List list = new ArrayList();
  • Not type-safe

  • Avoid in modern code


12. Difference between <?> and <Object>

<?>

  • Unknown type

  • Cannot add elements

<Object>

  • Specific type Object

  • Can add any object


13. What is Multiple Bounds in Generics?

You can restrict with multiple bounds.

class Test<T extends Number & Comparable<T>> {
}

T must extend Number and implement Comparable.


14. Real-Time Usage of Generics

Used in:

  • Collection framework (List<String>)

  • Repository layers

  • Service layers

  • Utility methods

  • Spring Data JPA repositories

Example:

public interface Repository<T> {
void save(T entity);
}

Frequently Asked Interview Questions

  • What is type erasure?

  • Why primitive types not allowed?

  • Explain PECS principle

  • Difference between extends and super

  • What is raw type?

  • Can we overload generic methods?


Strong Interview Closing Line

Generics provide:

  • Type safety

  • Compile-time checking

  • Better readability

  • Cleaner and reusable code



8️⃣ Multithreading


1. What is Multithreading?

Multithreading is the process of executing multiple threads simultaneously within a single process.

Benefits:

  • Better CPU utilization

  • Improved performance

  • Parallel task execution

  • Responsive applications

  • Background processing (Web servers, APIs, microservices)


2. What is a Thread?

A thread is the smallest unit of execution within a process.

Each thread has:

  • Independent execution path

  • Own stack memory

  • Shared heap memory

Threads within the same process share resources.


3. Difference between Process and Thread

Process

  • Independent program in execution

  • Has its own memory space

  • Heavyweight

  • Communication between processes is costly (IPC)

  • Example: Two separate running applications

Thread

  • Smallest unit of execution inside a process

  • Shares memory with other threads

  • Lightweight

  • Faster communication

  • Example: Multiple tasks inside same application

Interview Line:
Process is an independent execution unit, while a thread is a lightweight execution unit within a process.


4. How to create a Thread in Java?

Method 1: Extending Thread

class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread t = new MyThread();
t.start();

Method 2: Implementing Runnable (Preferred)

class MyTask implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
Thread t = new Thread(new MyTask());
t.start();

Why Runnable Preferred?

  • Better design

  • Supports multiple inheritance

  • Used with Executor framework


5. Difference between start() and run()

  • start() → Creates new thread and calls run()

  • run() → Normal method call (no new thread)

Calling run() directly does not create a new thread.


6. Thread Life Cycle

States:

  • New

  • Runnable

  • Running

  • Blocked / Waiting

  • Terminated


7. What is Race Condition?

Race condition occurs when:

  • Multiple threads access shared data

  • At least one thread modifies the data

  • Final result depends on execution order

Example:

count++;

This is not atomic (read → modify → write).

Race conditions lead to inconsistent results.


8. What is synchronized?

  • Controls access to shared resources

  • Only one thread executes synchronized block

  • Prevents race condition

  • Uses intrinsic lock

synchronized void increment() {
count++;
}

9. What is volatile?

  • Ensures visibility across threads

  • Prevents caching

  • Guarantees latest value

  • Does NOT guarantee atomicity

volatile boolean flag = true;

10. Difference between synchronized and volatile

synchronizedvolatile
Ensures mutual exclusionEnsures visibility
Uses lockingNo locking
Prevents race conditionDoes not prevent race condition
SlowerFaster

11. What is Deadlock?

Deadlock occurs when:

  • Two or more threads wait for each other’s locks

  • None can proceed

Example scenario:

Thread A holds Lock1 → waiting for Lock2
Thread B holds Lock2 → waiting for Lock1


12. How to Prevent Deadlock?

Deadlock occurs when:

  • Two or more threads wait for each other’s locks

  • None can proceed

Prevention Techniques:

  • Acquire locks in consistent order

  • Avoid nested locks

  • Use tryLock() instead of synchronized

  • Use timeout while acquiring locks

  • Minimize synchronized block scope

Example using ReentrantLock:

ReentrantLock lock = new ReentrantLock();

if (lock.tryLock()) {
try {
// critical section
} finally {
lock.unlock();
}
}

13. Difference between synchronized and ReentrantLock

synchronizedReentrantLock
KeywordClass
Lock released automaticallyMust manually unlock
No fairness optionSupports fairness policy
No tryLock() supportSupports tryLock()
No interruptible lockinglockInterruptibly() supported
Less flexibleMore flexible and powerful

When to Use

  • synchronized → Simple use cases

  • ReentrantLock → Advanced control, timeout, fairness required


14. What is Thread Pool?

Thread pool is a collection of reusable threads.

  • Avoids frequent thread creation

  • Improves performance

  • Controls concurrency

  • Managed by Executor framework

Used in:

  • Web servers

  • Microservices

  • Background job processing


15. What is Executor Framework?

Executor Framework is part of java.util.concurrent.

It separates:

  • Task submission

  • Thread management

Instead of manually creating threads, it provides:

  • Executor

  • ExecutorService

  • ScheduledExecutorService

Benefits:

  • Thread reuse

  • Better resource management

  • Controlled concurrency

  • Cleaner code

Common Executor Types:

  • newFixedThreadPool(n)

  • newCachedThreadPool()

  • newSingleThreadExecutor()

  • newScheduledThreadPool(n)

Example:

ExecutorService executor =
Executors.newFixedThreadPool(3);

for (int i = 0; i < 5; i++) {
executor.submit(() ->
System.out.println(Thread.currentThread().getName()));
}

executor.shutdown();

16. Callable vs Runnable

Runnable

  • No return value

  • Cannot throw checked exception

  • run() method

Used in real-time when:

  • Sending email

  • Logging

  • Fire-and-forget background tasks

  • No result needed

Example:

executor.submit(() -> System.out.println("Task executed"));

Callable

  • Returns value

  • Can throw checked exception

  • call() method

Used in real-time when:

  • Database query returning result

  • REST API call returning response

  • Complex calculations

  • Need exception handling

Example:

Callable<Integer> task = () -> {
return 100;
};

Future<Integer> result = executor.submit(task);
System.out.println(result.get());

17. What is Future?

Future represents result of asynchronous computation.

Key Methods:

  • get() → waits and returns result

  • get(timeout, unit) → waits with timeout

  • isDone() → checks completion

  • cancel() → cancels task

  • isCancelled() → checks if cancelled

Example:

ExecutorService executor =
Executors.newSingleThreadExecutor();

Future<Integer> future =
executor.submit(() -> 200);

if (!future.isDone()) {
System.out.println("Waiting...");
}

System.out.println(future.get());

executor.shutdown();

Important Points:

  • get() blocks calling thread

  • Used for async result retrieval

  • Helps coordinate parallel tasks


18. What is CompletableFuture?

Introduced in Java 8.

Used for:

  • Asynchronous programming

  • Non-blocking execution

  • Chaining multiple async tasks

Advantages:

  • Functional style

  • Non-blocking callbacks

  • Combine multiple futures

  • Better than traditional Future

Example:

CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(result -> result + " World")
.thenAccept(System.out::println);

Real-Time Usage:

  • Calling multiple microservices in parallel

  • Async REST APIs

  • Background data processing


19. What is ForkJoinPool?

ForkJoinPool is a special thread pool designed for parallel processing.

  • Used for divide-and-conquer problems

  • Implements work-stealing algorithm

  • Introduced in Java 7

  • Used internally by parallel streams

Example:

ForkJoinPool pool = new ForkJoinPool();
pool.submit(() -> System.out.println("Task"));

Used In:

  • Parallel streams

  • Recursive tasks

  • CPU-intensive workloads

Interview Point:

Parallel streams internally use ForkJoinPool.


20. What are Virtual Threads (Java 21)?

Introduced as stable in Java 21.

  • Lightweight threads

  • Managed by JVM

  • Thousands of threads possible

  • Ideal for IO-bound applications

  • Simplifies concurrency

Example:

Thread.startVirtualThread(() -> {
System.out.println("Virtual Thread running");
});

Real-Time Use:

  • High traffic APIs

  • Microservices

  • IO-intensive systems

Interview Line:

Virtual threads are lightweight JVM-managed threads enabling massive concurrency with simpler code.


21. What is Atomic Class?

From java.util.concurrent.atomic.

  • Lock-free

  • Uses CAS

  • Prevents race condition

Example:

AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet();


22. Platform Thread vs Virtual Thread

Platform ThreadVirtual Thread
OS managedJVM managed
HeavyweightLightweight
LimitedMillions possible
Expensive context switchCheap

23. What is ThreadLocal?

Provides thread-specific variable.

ThreadLocal<Integer> local = new ThreadLocal<>();
local.set(100);
System.out.println(local.get());

Each thread gets separate copy.

Used in:

  • User session

  • Transactions


24. What is Producer-Consumer problem?

One thread produces data
Another consumes data

Solved using:

  • wait/notify

  • BlockingQueue (modern)


9️⃣ Object Class Methods


1. What is Object class in Java?

Answer:

Object class is the root class of Java.

  • Present in java.lang package

  • Every class in Java implicitly extends Object

  • Provides common methods for all objects

Interview Line:

Object is the superclass of all Java classes.


2. What are the important methods of Object class?

Answer:

Common Object class methods:

  • toString()

  • equals(Object obj)

  • hashCode()

  • clone()

  • finalize()

  • getClass()

  • wait()

  • notify()

  • notifyAll()


3. What is toString() method?

Answer:

Returns string representation of an object.

Default implementation:

  • Returns class name + @ + hashcode

Example:

class Person {
String name;

Person(String name) {
this.name = name;
}

public String toString() {
return "Person{name='" + name + "'}";
}
}

Used for:

  • Debugging

  • Logging

  • Printing object details


4. What is equals() method?

Answer:

Used to compare two objects for equality.

Default behavior:

  • Compares memory references

Custom implementation compares object content.

Example:

class Person {
String name;

public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Person)) return false;
Person p = (Person) obj;
return this.name.equals(p.name);
}
}

Used in:

  • Collections

  • Searching

  • Business logic comparison


5. What is hashCode() method?

Answer:

Returns integer hash value of object.

Rules:

  • If two objects are equal → hashCode must be same

  • If hashCodes are different → objects are definitely different

Example:

public int hashCode() {
return name.hashCode();
}

Used in:

  • HashMap

  • HashSet

  • Hashtable


6. What is the contract between equals() and hashCode()?

Answer:

Rules:

  • If equals() returns true → hashCode must be same

  • If equals() returns false → hashCode may or may not be same

  • Must override both together

Failing to follow contract causes issues in HashMap and HashSet.


7. What is clone() method?

Answer:

Used to create copy of an object.

Class must implement Cloneable interface.

Example:

class Person implements Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

Types of cloning:

  • Shallow Copy

  • Deep Copy


8. What is shallow copy?

Answer:

Copies object but not referenced objects.

Only references are copied.


9. What is deep copy?

Answer:

Creates copy of object and its referenced objects.

Used when:

  • Complete independent copy is needed


10. What is finalize() method?

Answer:

Called by Garbage Collector before object destruction.

Used for:

  • Cleanup operations

Note:

  • Deprecated in modern Java

  • Not recommended for resource cleanup

Better alternative:

  • try-with-resources


11. What is getClass() method?

Answer:

Returns runtime class of object.

Example:

Person p = new Person("John");
System.out.println(p.getClass());

Used in:

  • Reflection

  • Frameworks

  • Logging


12. What are wait(), notify(), notifyAll() methods?

Answer:

Used for inter-thread communication.

wait()

  • Makes current thread wait

  • Must be called inside synchronized block

notify()

  • Wakes up one waiting thread

notifyAll()

  • Wakes up all waiting threads

Example:

synchronized(obj) {
obj.wait();
obj.notify();
}

Used in:

  • Producer-Consumer problem

  • Multithreading coordination


Frequently Asked Interview Questions

Difference between == and equals()?

Why override hashCode when overriding equals?

Why is finalize deprecated?

Difference between shallow and deep copy?


Strong Interview Closing Line

Object class provides:

  • Equality checking

  • Hashing support

  • String representation

  • Cloning

  • Thread communication support

Every Java object inherits these fundamental behaviors.




🔟 File I/O and NIO


🔹 File I/O (java.io)


1. What is File I/O in Java?

Answer:

File I/O (Input/Output) is used to read and write data to files.

Located in:

  • java.io package

Used for:

  • Reading files

  • Writing files

  • Handling streams

  • Serialization


2. What are Streams in Java I/O?

Answer:

Stream represents flow of data.

Two types:

  • InputStream → Reads data

  • OutputStream → Writes data

Character streams:

  • Reader

  • Writer


3. Difference between Byte Stream and Character Stream

Answer:

Byte Stream:

  • Used for binary data

  • Classes: InputStream, OutputStream

  • Example: Image, PDF

Character Stream:

  • Used for text data

  • Classes: Reader, Writer

  • Handles Unicode automatically


4. What is File class?

Answer:

File class represents file or directory path.

Used to:

  • Create file

  • Delete file

  • Check existence

  • Get file properties

Example:

File file = new File("test.txt");
System.out.println(file.exists());

File class does not read/write data, it only handles metadata.


5. How to read a file using FileInputStream?

Answer:

FileInputStream fis = new FileInputStream("test.txt");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();

Reads file byte by byte.


6. How to write to a file using FileOutputStream?

Answer:

FileOutputStream fos = new FileOutputStream("test.txt");
fos.write("Hello Java".getBytes());
fos.close();

Writes bytes into file.


7. What is BufferedReader and BufferedWriter?

Answer:

Used to improve performance using buffering.

BufferedReader:

BufferedReader br =
new BufferedReader(new FileReader("test.txt"));

String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

BufferedWriter:

BufferedWriter bw =
new BufferedWriter(new FileWriter("test.txt"));

bw.write("Hello");
bw.close();

Benefits:

  • Faster I/O

  • Reduces disk access


8. What is Serialization?

Answer:

Serialization converts object into byte stream.

Used to:

  • Save object state

  • Send object over network

Class must implement Serializable.

Example:

class Person implements Serializable {
String name;
}

9. What is transient keyword?

Answer:

transient prevents field from being serialized.

Example:

transient String password;

Used for:

  • Sensitive data

  • Temporary fields


🔹 NIO (New I/O)


10. What is NIO?

Answer:

NIO stands for New Input/Output.

Introduced in Java 1.4.

Located in:

  • java.nio package

Provides:

  • Non-blocking I/O

  • Buffer-based operations

  • Channels


11. What are main components of NIO?

Answer:

  • Buffer

  • Channel

  • Selector


12. What is Buffer in NIO?

Answer:

Buffer is container for data.

Common types:

  • ByteBuffer

  • CharBuffer

  • IntBuffer

Example:

ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello".getBytes());
buffer.flip();

13. What is Channel in NIO?

Answer:

Channel represents connection to file or socket.

Examples:

  • FileChannel

  • SocketChannel

  • ServerSocketChannel

Example:

FileChannel channel =
FileChannel.open(Path.of("test.txt"));

14. What is Selector in NIO?

Answer:

Selector allows one thread to manage multiple channels.

Used for:

  • Non-blocking I/O

  • High-performance servers

Common in:

  • Web servers

  • Networking applications


15. Difference between I/O and NIO

Answer:

I/O:

  • Stream-based

  • Blocking

  • One thread per connection

NIO:

  • Buffer-based

  • Non-blocking

  • One thread can manage multiple connections


16. What is Files class in NIO?

Answer:

Files class provides utility methods.

Common methods:

  • readAllLines()

  • readString()

  • write()

  • writeString()

Example:

String content =
Files.readString(Path.of("test.txt"));

Files.writeString(Path.of("test.txt"), "Hello");

17. What is Path in NIO?

Answer:

Path represents file path.

Example:

Path path = Path.of("test.txt");

Used with Files and FileChannel.


18. What is try-with-resources?

Answer:

Automatically closes resources.

Example:

try (BufferedReader br =
new BufferedReader(new FileReader("test.txt"))) {

System.out.println(br.readLine());
}

Prevents resource leaks.


19. Serializable vs Externalizable

Serializable:

  • Default serialization

  • JVM handles

Externalizable:

  • Manual control

  • Must override writeExternal & readExternal


20. What is RandomAccessFile?

Allows reading/writing at specific file position.

RandomAccessFile file =
new RandomAccessFile("test.txt", "rw");

file.seek(5);
file.writeBytes("Java");

Frequently Asked Interview Questions

Difference between File and Path?

What is blocking vs non-blocking I/O?

Why NIO is faster?

Difference between readAllLines and readString?

When to use Serialization?


Strong Interview Closing Line

File I/O focuses on:

  • Stream-based blocking operations

NIO focuses on:

  • Buffer-based non-blocking operations

  • High-performance networking

  • Modern file handling APIs


1️⃣1️⃣ Java 8 Features


1. What are the major features introduced in Java 8?

Java 8 introduced functional programming features into Java.

Major features:

  • Lambda Expressions

  • Functional Interfaces

  • Stream API

  • Default Methods in Interfaces

  • Static Methods in Interfaces

  • Method References

  • Optional Class

  • CompletableFuture

  • New Date and Time API (java.time)

Interview Line: Java 8 introduced functional programming capabilities to Java.



🔹 Lambda Expressions


2. What is a Lambda Expression?

A lambda expression is a concise way to represent an anonymous function.

Syntax:

(parameters) -> expression

Example without lambda:

Runnable r = new Runnable() {
public void run() {
System.out.println("Running");
}
};

With lambda:

Runnable r = () -> System.out.println("Running");

3. Why do we need Lambda Expressions?

  • Reduce boilerplate code

  • Improve readability

  • Enable functional programming

  • Used heavily with Stream API

  • Replace anonymous classes


4. Difference between Lambda and Anonymous Class

LambdaAnonymous Class
Less codeMore boilerplate
No new scopeCreates new scope
Cannot define multiple methodsCan define multiple methods
Works only with functional interfacesCan extend class or interface


🔹 Functional Interface


5. What is a Functional Interface?

A Functional Interface contains exactly one abstract method.

It can contain:

  • Multiple default methods

  • Multiple static methods

  • Only one abstract method

Example:

@FunctionalInterface
interface MyInterface {
void show();
}

6. Why use @FunctionalInterface?

  • Ensures only one abstract method

  • Compile-time validation

  • Improves readability


7. Common Built-in Functional Interfaces

Located in java.util.function package:

  • Predicate<T> → boolean test(T t)

  • Function<T,R> → R apply(T t)

  • Consumer<T> → void accept(T t)

  • Supplier<T> → T get()

Examples:

Predicate<Integer> p = x -> x > 10;
Function<String, Integer> f = s -> s.length();
Consumer<String> c = s -> System.out.println(s);
Supplier<Double> s = () -> Math.random();


🔹 Method References


8. What is Method Reference?

Method reference is a shorter form of lambda expression.

Syntax:

ClassName::methodName

Example:

list.forEach(System.out::println);

Types:

  • Static method reference

  • Instance method reference

  • Constructor reference



🔹 Stream API


9. What is Stream API?

Stream API is used to process collections in a functional style.

Features:

  • Introduced in Java 8

  • Internal iteration

  • Lazy evaluation

  • Does not modify source

  • Supports parallel processing


10. Difference between Collection and Stream

CollectionStream
Stores dataProcesses data
External iterationInternal iteration
Can be reusedSingle-use
Can modifyCannot modify source

11. How to create a Stream?

From Collection:

list.stream();

Parallel stream:

list.parallelStream();

From Array:

Arrays.stream(arr);

12. Intermediate Operations in Stream

  • filter()

  • map()

  • flatMap()

  • sorted()

  • distinct()

  • limit()

  • skip()

Characteristics:

  • Return Stream

  • Lazy

  • Do not execute until terminal operation

Example:

list.stream()
.filter(s -> s.startsWith("J"))
.map(String::toUpperCase)
.sorted();

13. Terminal Operations in Stream

  • collect()

  • forEach()

  • reduce()

  • count()

  • anyMatch()

  • findFirst()

  • findAny()

They:

  • Produce result

  • Trigger execution

Example:

List<String> result =
list.stream()
.filter(s -> s.length() > 4)
.collect(Collectors.toList());

14. Difference between map() and flatMap()

map():

  • One-to-one mapping

flatMap():

  • One-to-many mapping

  • Flattens nested structures

Example:

List<List<String>> list = ...;

list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());

15. What is reduce()?

reduce() combines elements into single result.

Example:

int sum = list.stream()
.reduce(0, (a, b) -> a + b);

16. What is Optional?

Optional is a container that may or may not contain value.

Used to avoid NullPointerException.

Example:

Optional<String> name =
Optional.ofNullable("Java");

name.ifPresent(System.out::println);

17. Difference between findFirst() and findAny()

  • findFirst() → Returns first element

  • findAny() → Returns any element (better for parallel stream)


18. What is Parallel Stream?

  • Uses ForkJoinPool

  • Processes elements in parallel

  • Suitable for CPU-intensive tasks

list.parallelStream()
.forEach(System.out::println);

19. What is Lazy Evaluation?

Stream operations execute only when a terminal operation is invoked.

Intermediate operations are lazy.

20. What is Collectors?

Collectors is a utility class used with collect().

Common methods:

  • toList()

  • toSet()

  • joining()

  • groupingBy()

  • partitioningBy()

Example:

Map<Integer, List<String>> grouped =
list.stream()
.collect(Collectors.groupingBy(String::length));

🔹 CompletableFuture


21. What is CompletableFuture?

Introduced in Java 8.

Used for:

  • Asynchronous programming

  • Non-blocking operations

  • Chaining async tasks

Advantages:

  • Non-blocking

  • Functional style

  • Combine multiple futures

  • Better than traditional Future

Example:

CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);

Used in:

  • Microservices

  • Async REST calls

  • Parallel API calls

🔹 Default and Static Methods in Interface


22. What are Default Methods?

Default methods allow method implementation inside interface.

Purpose:

  • Backward compatibility

  • Evolving APIs

Example:

interface Vehicle {
default void start() {
System.out.println("Vehicle started");
}
}

Important Points:

  • Can be overridden

  • If multiple interfaces have same method → class must override


23. What are Static Methods in Interface?

Static methods belong to interface.

  • Cannot be overridden

  • Called using interface name

Example:

interface MathUtil {
static int add(int a, int b) {
return a + b;
}
}

int result = MathUtil.add(5, 3);

🔹 Date and Time API (java.time)


24. Why new Date and Time API introduced?

Problems with old API:

  • Mutable

  • Not thread-safe

  • Poor design

Java 8 introduced java.time package.


25. Important Classes in java.time

  • LocalDate

  • LocalTime

  • LocalDateTime

  • ZonedDateTime

  • Period

  • Duration

  • DateTimeFormatter


26. What is LocalDate?

Represents date only.

LocalDate date = LocalDate.now();
LocalDate custom = LocalDate.of(2025, 1, 10);

27. What is LocalTime?

Represents time only.

LocalTime time = LocalTime.now();

28. What is LocalDateTime?

Represents date and time.

LocalDateTime dateTime =
LocalDateTime.now();

29. What is ZonedDateTime?

Date and time with timezone.

ZonedDateTime zoned =
ZonedDateTime.now();

30. What is Period and Duration?

Period → Date-based difference
Duration → Time-based difference

Example:

Period period =
Period.between(LocalDate.now(),
LocalDate.of(2026, 1, 1));

Duration duration =
Duration.between(LocalTime.now(),
LocalTime.now().plusHours(2));

31. What is DateTimeFormatter?

Used for formatting and parsing.

DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd-MM-yyyy");

String formatted =
LocalDate.now().format(formatter);

32. Key Advantages of java.time API

  • Immutable

  • Thread-safe

  • Clear API

  • Easy arithmetic

  • Better timezone handling


33. What is the difference between map() and peek()?

map()

  • Used to transform each element in a stream

  • Returns a new modified stream

  • Commonly used for data conversion

  • Functional and pure transformation

  • Part of intermediate operations


List<String> list = Arrays.asList("java", "spring");

List<String> result =
list.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

System.out.println(result);
// Output: [JAVA, SPRING]


peek()

  • Used mainly for debugging

  • Performs side-effect action

  • Does not modify elements

  • Intermediate operation

  • Often used for logging

List<String> list = Arrays.asList("java", "spring");

List<String> result =
list.stream()
.peek(System.out::println)
.collect(Collectors.toList());

// Output:
// java
// spring

Interview Line:
map() transforms data, peek() inspects data.


34. What is the difference between sorted() and sort()?

sorted()

  • Stream method

  • Returns new sorted stream

  • Does not modify original collection

  • Functional style

  • Can accept Comparator


List<Integer> list = Arrays.asList(5, 2, 8, 1);

List<Integer> sorted =
list.stream()
.sorted()
.collect(Collectors.toList());

System.out.println(sorted);
// Output: [1, 2, 5, 8]

System.out.println(list);
// Output: [5, 2, 8, 1]

sort()

  • List method

  • Modifies original list

  • In-place sorting

  • Available via Collections or List

  • Requires mutable list


List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1));

Collections.sort(list);

System.out.println(list);
// Output: [1, 2, 5, 8]

Interview Line:
sorted() is non-mutating, sort() modifies original list.


35. What is the difference between groupingBy() and partitioningBy()?

groupingBy()

  • Groups elements based on classification function

  • Can create multiple groups

  • Returns Map<K, List<V>>

  • Flexible grouping logic

  • Most commonly used collector


List<String> list = Arrays.asList("Java", "Spring", "Boot", "API");

Map<Integer, List<String>> grouped =
list.stream()
.collect(Collectors.groupingBy(String::length));

System.out.println(grouped);
// Output: {4=[Java, Boot], 6=[Spring], 3=[API]}

partitioningBy()

  • Special case of groupingBy

  • Splits into only two groups

  • Based on boolean condition

  • Returns Map<Boolean, List<V>>

  • Useful for even/odd, pass/fail cases

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Map<Boolean, List<Integer>> partitioned =
numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));

System.out.println(partitioned);
// Output: {false=[1, 3, 5], true=[2, 4]}

Interview Line:
groupingBy → multiple buckets
partitioningBy → true/false split


36. What is the difference between Collector and Collectors?

Collector

  • Interface in java.util.stream

  • Defines how reduction operation works

  • Used by collect() method

  • Specifies accumulation logic

  • Advanced custom collectors can be created

Signature:

<R, A> R collect(Collector<? super T, A, R> collector);

Collectors

  • Utility class

  • Provides ready-made Collector implementations

  • Contains factory methods

  • Simplifies common aggregation operations

  • Used in almost all stream reductions

List<String> list = Arrays.asList("Java", "Spring");

String result =
list.stream()
.collect(Collectors.joining(", "));

System.out.println(result);
// Output: Java, Spring

Interview Line:
Collector is an interface; Collectors provides implementations.


1️⃣2️⃣ Java 11 Features


1. What are the major features introduced in Java 11?

Answer:

Java 11 is a Long Term Support (LTS) release.

Major features:

  • New String methods

  • HTTP Client API

  • Local-Variable Syntax for Lambda

  • Optional enhancements

  • Files utility methods

  • Collection toArray() improvement

  • Nest-Based Access Control

  • Java Flight Recorder

  • Removal of Java EE and CORBA modules

Interview Line:

Java 11 is an LTS release focused on stability, modern APIs, and performance improvements.


2. Why is Java 11 important?

Answer:

  • Long Term Support (LTS) version

  • Enterprise-ready stability

  • Improved performance

  • Modern HTTP client

  • Cleaner and improved APIs


3. What new methods were added to String in Java 11?

Answer:

New methods added:

  • isBlank()

  • lines()

  • strip()

  • stripLeading()

  • stripTrailing()

  • repeat(int count)

isBlank()

Used to check if string is empty or contains only whitespace.

String str = " ";
System.out.println(str.isBlank());

strip(), stripLeading(), stripTrailing()

  • Improved version of trim()

  • Unicode aware

String str = " Java ";
System.out.println(str.strip());

lines()

  • Returns Stream of lines

  • Useful for multi-line string processing

String text = "Java\nSpring\nBoot";
text.lines().forEach(System.out::println);

repeat()

  • Repeats string specified number of times

System.out.println("Java".repeat(3));

4. What is the new HTTP Client API in Java 11?

Answer:

Java 11 introduced new HttpClient in java.net.http package.

Used to replace old HttpURLConnection.

Features:

  • Supports HTTP/1.1 and HTTP/2

  • Supports synchronous requests

  • Supports asynchronous requests

  • Supports WebSocket

  • Cleaner API

Example – Synchronous Request

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.GET()
.build();

HttpResponse<String> response =
client.send(request,
HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());

Example – Asynchronous Request

client.sendAsync(request,
HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);

5. What is Local-Variable Syntax for Lambda?

Answer:

Java 11 allows usage of var inside lambda parameters.

Used to:

  • Improve readability

  • Allow annotations in lambda parameters

Example:

(var x, var y) -> x + y

6. What enhancements were added to Optional?

Answer:

New method added:

  • isEmpty()

Opposite of isPresent().

Optional<String> opt = Optional.empty();
System.out.println(opt.isEmpty());

7. What new methods were added in Files class?

Answer:

New methods:

  • readString()

  • writeString()

Used to simplify file operations.

Example:

String content = Files.readString(Path.of("file.txt"));
Files.writeString(Path.of("file.txt"), "Hello Java 11");

8. What is Collection toArray() improvement in Java 11?

Answer:

Improved way to convert collection to array.

Before Java 11:

String[] arr = list.toArray(new String[0]);

Java 11 improved version:

String[] arr = list.toArray(String[]::new);
  • Cleaner

  • More readable


9. What is Nest-Based Access Control?

Answer:

Allows nested classes to access private members of outer class directly.

Benefits:

  • Improved performance

  • Cleaner bytecode

  • Better access control


10. What is Java Flight Recorder?

Answer:

Java Flight Recorder is a low-overhead profiling and monitoring tool.

Used for:

  • Performance analysis

  • Debugging production issues

  • Monitoring JVM behavior

Integrated into OpenJDK from Java 11.


11. What was removed in Java 11?

Answer:

Removed features:

  • Java EE modules

  • CORBA

  • Deployment stack

Requires adding external dependencies now.


Strong Interview Closing Line

Java 11 focuses on:

  • Enterprise stability (LTS)

  • Modern HTTP client

  • Better String handling

  • Improved file utilities

  • Cleaner APIs


1️⃣3️⃣ Java 17 Features


1. What are the major features introduced in Java 17?

Answer:

Java 17 is a Long Term Support (LTS) release.

Major features:

  • Sealed Classes

  • Pattern Matching for instanceof

  • Records (Standardized)

  • Strong encapsulation of JDK internals

  • New macOS rendering pipeline

  • Foreign Function & Memory API (Incubator)

  • Removal of deprecated APIs

  • Performance and security improvements

Interview Line:

Java 17 is an LTS release focused on stronger encapsulation, better domain modeling, and cleaner syntax improvements.


2. What are Sealed Classes?

Answer:

Sealed classes restrict which classes can extend or implement them.

Used to:

  • Control inheritance

  • Improve domain modeling

  • Increase security

  • Prevent unwanted subclassing

Syntax:

public sealed class Shape
permits Circle, Rectangle {
}

Subclasses must declare one of the following:

final class Circle extends Shape { }
non-sealed class Rectangle extends Shape { }

Allowed modifiers:

  • final

  • sealed

  • non-sealed


Benefits:

  • Better control over class hierarchy

  • Useful in frameworks and APIs

  • Improves maintainability


3. What is Pattern Matching for instanceof?

Answer:

Simplifies type checking and casting.

Before Java 17:

if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}

Java 17:

if (obj instanceof String s) {
System.out.println(s.length());
}

Benefits:

  • Removes explicit casting

  • Reduces boilerplate

  • Improves readability

  • Safer type handling


4. What are Records?

Answer:

Records are special classes used to represent immutable data.

Used for:

  • Data transfer objects (DTOs)

  • Value objects

  • Immutable models

Example:

public record Person(String name, int age) {}

Automatically generates:

  • Constructor

  • Getter methods

  • equals()

  • hashCode()

  • toString()

Characteristics:

  • Immutable

  • Final

  • Cannot extend other classes

  • Can implement interfaces

Benefits:

  • Less boilerplate

  • Cleaner code

  • Ideal for microservices and APIs


5. What is Strong Encapsulation in Java 17?

Answer:

Java 17 strongly encapsulates internal JDK APIs.

  • Internal APIs are not accessible by default

  • Improves security

  • Prevents accidental misuse

  • Encourages proper modular design

This builds on the Java Module System introduced in Java 9.


6. What improvements were made to Security in Java 17?

Answer:

  • Removed deprecated security features

  • Disabled weak cryptographic algorithms

  • Strong encapsulation of internal APIs

  • Improved TLS support

Improves enterprise-level security.


7. What was removed in Java 17?

Answer:

Removed features:

  • RMI Activation

  • Deprecated and obsolete APIs

  • Experimental AOT and JIT compiler

Purpose:

  • Cleaner JDK

  • Reduced maintenance overhead

  • Better long-term stability


8. Why is Java 17 important?

Answer:

  • Long Term Support (LTS) version

  • Stable for enterprise applications

  • Modern language improvements

  • Improved performance

  • Enhanced security

Widely used in:

  • Spring Boot 3

  • Enterprise microservices

  • Modern backend systems


Strong Interview Closing Line

Java 17 focuses on:

  • Controlled inheritance with Sealed Classes

  • Cleaner syntax with Pattern Matching

  • Immutable data modeling using Records

  • Stronger security and encapsulation

  • Enterprise-ready LTS stability




1️⃣4️⃣ Java 21 Features


1. What are the major features introduced in Java 21?

Answer:

Java 21 is a Long Term Support (LTS) release.

Major standard features:

  • Virtual Threads

  • Pattern Matching for switch

  • Record Patterns

  • Sequenced Collections

  • Scoped Values

  • Structured Concurrency

  • Foreign Function & Memory API

  • Garbage Collector improvements

  • Performance and security enhancements

Interview Line:

Java 21 is an LTS release focused on high concurrency, modern pattern matching, and simplified parallel programming.


2. What are Virtual Threads?

Answer:

Virtual Threads are lightweight threads managed by the JVM.

They are part of Project Loom.

Used to:

  • Handle high concurrency

  • Improve scalability

  • Simplify concurrent programming

  • Reduce complexity of thread pools

Example:

Thread.startVirtualThread(() -> {
System.out.println("Virtual Thread running");
});

Benefits:

  • Can create thousands or millions of threads

  • Ideal for IO-bound applications

  • Lower memory usage than platform threads

  • Simpler alternative to reactive programming

Used in:

  • Microservices

  • High-traffic APIs

  • Backend servers


3. What is Structured Concurrency?

Answer:

Structured Concurrency simplifies managing multiple concurrent tasks.

It treats related tasks as a single unit of work.

Benefits:

  • Better error handling

  • Automatic cancellation of related tasks

  • Cleaner resource management

  • Improved readability

Concept:

If one task fails, other related tasks can be cancelled together.


4. What are Scoped Values?

Answer:

Scoped Values provide a safe alternative to ThreadLocal.

Used to:

  • Share immutable data across threads

  • Avoid memory leaks

  • Improve performance

Advantages over ThreadLocal:

  • Immutable

  • Limited scope

  • No accidental data retention

Useful in:

  • Virtual thread environments

  • Request-scoped data


5. What is Pattern Matching for switch?

Answer:

Enhances switch statement to support type patterns.

Example:

switch (obj) {
case String s -> System.out.println(s.length());
case Integer i -> System.out.println(i * 2);
default -> System.out.println("Unknown");
}

Benefits:

  • Cleaner syntax

  • Reduces if-else chains

  • Type-safe pattern matching

  • Improved readability


6. What are Record Patterns?

Answer:

Record Patterns allow destructuring of record objects.

Example:

record Person(String name, int age) {}

if (obj instanceof Person(String name, int age)) {
System.out.println(name + " " + age);
}

Benefits:

  • Extract components directly

  • Cleaner pattern matching

  • Better domain modeling


7. What are Sequenced Collections?

Answer:

Java 21 introduces SequencedCollection interface.

Provides consistent ordering operations.

New methods:

  • getFirst()

  • getLast()

  • addFirst()

  • addLast()

  • reversed()

Applies to:

  • List

  • Set

  • Map

Benefits:

  • Unified ordering API

  • Cleaner collection handling

  • Improved consistency


8. What is Foreign Function & Memory API?

Answer:

Provides safe and efficient access to:

  • Native libraries (C code)

  • Off-heap memory

Replaces many JNI use cases.

Benefits:

  • Better performance

  • Safer memory access

  • Cleaner native interoperation

  • Improved stability


9. What improvements were made to Garbage Collection?

Answer:

Java 21 improves:

  • ZGC

  • Shenandoah GC

  • Large heap handling

  • Reduced pause times

  • Better scalability

Designed for:

  • Cloud-native systems

  • High-throughput applications

  • Large memory workloads


10. Why is Java 21 important?

Answer:

  • LTS release

  • Massive scalability using Virtual Threads

  • Simplified concurrency model

  • Modern pattern matching

  • Better performance and GC

Suitable for:

  • Enterprise systems

  • Microservices

  • High-concurrency applications

  • Cloud-native architecture


Strong Interview Closing Line

Java 21 focuses on:

  • Massive concurrency with Virtual Threads

  • Cleaner structured parallel programming

  • Advanced pattern matching

  • Enterprise-ready LTS stability




1️⃣5️⃣ JVM Internals


1. What is JVM?

Answer:

JVM (Java Virtual Machine) is a runtime engine that executes Java bytecode.

Responsibilities:

  • Loads class files

  • Verifies bytecode

  • Executes code

  • Manages memory

  • Performs Garbage Collection

  • Provides platform independence

Interview Line:

JVM is responsible for executing bytecode and managing memory for Java applications.


2. What are the main components of JVM?

Answer:

JVM consists of:

  • Class Loader Subsystem

  • Runtime Data Areas

  • Execution Engine

  • Native Method Interface (JNI)

  • Native Libraries



🔹 Class Loader Subsystem


3. What is Class Loader?

Answer:

Class Loader loads .class files into JVM memory.

Steps involved:

  • Loading

  • Linking

    • Verification

    • Preparation

    • Resolution

  • Initialization


4. What are types of Class Loaders?

Answer:

  • Bootstrap ClassLoader

  • Extension ClassLoader

  • Application ClassLoader

Bootstrap loads core Java classes like java.lang.*

Application ClassLoader loads classes from classpath.


5. What is Parent Delegation Model?

Answer:

Class loading follows delegation hierarchy.

Process:

  • Child asks parent to load class

  • Parent tries first

  • If not found, child loads

Prevents:

  • Duplicate classes

  • Security issues



🔹 JVM Memory Structure


6. What are Runtime Data Areas in JVM?

Answer:

JVM memory is divided into:

  • Heap

  • Stack

  • Method Area

  • Program Counter (PC Register)

  • Native Method Stack


7. What is Heap Memory?

Answer:

Heap stores:

  • Objects

  • Instance variables

Characteristics:

  • Shared among threads

  • Garbage collected

Heap is divided into:

  • Young Generation

    • Eden

    • Survivor S0

    • Survivor S1

  • Old Generation


8. What is Stack Memory?

Answer:

Each thread has its own stack.

Stores:

  • Local variables

  • Method calls

  • Partial results

If stack memory exceeds limit → StackOverflowError.


9. What is Method Area?

Answer:

Method Area stores:

  • Class metadata

  • Static variables

  • Runtime constant pool

  • Method bytecode

In Java 8+, Method Area is implemented as Metaspace.


10. What is Metaspace?

Answer:

Metaspace replaces PermGen (before Java 8).

  • Stores class metadata

  • Allocated from native memory

  • Automatically expands

Prevents OutOfMemoryError: PermGen space.


11. What is PC Register?

Answer:

Program Counter Register stores:

  • Address of current instruction

Each thread has its own PC register.


12. What is Native Method Stack?

Answer:

Used for:

  • Native methods

  • C/C++ calls via JNI



🔹 Execution Engine


13. What is Execution Engine?

Answer:

Execution Engine executes bytecode.

Components:

  • Interpreter

  • JIT Compiler

  • Garbage Collector

Interpreter executes code line by line.

JIT compiles frequently used code into native machine code for better performance.



🔹 Java Memory Model (JMM)


14. What is Java Memory Model?

Answer:

Java Memory Model defines how threads interact with memory.

Defines:

  • Visibility

  • Ordering

  • Atomicity

Ensures consistent behavior in multithreaded programs.


15. What is Visibility Problem?

Answer:

Occurs when:

  • One thread updates variable

  • Other thread cannot see updated value

Solution:

  • volatile

  • synchronized

  • Locks


16. What is Atomicity?

Answer:

Atomicity means operation happens completely or not at all.

Example:

count++;

Not atomic.

Solution:

  • Atomic classes

  • synchronized

  • Locks


17. What is happens-before relationship?

Answer:

Happens-before guarantees memory visibility.

Examples:

  • Unlock happens-before subsequent lock

  • Write to volatile happens-before read

  • Thread start happens-before execution


18. What is Instruction Reordering?

Answer:

Compiler and CPU may reorder instructions for optimization.

JMM prevents incorrect behavior using:

  • volatile

  • synchronized



🔹 Garbage Collection (GC)


19. What is Garbage Collection?

Answer:

Garbage Collection automatically removes unreachable objects from heap.

Benefits:

  • Automatic memory management

  • Prevents memory leaks

  • Improves application stability


20. How does Garbage Collection work?

Answer:

Basic steps:

  • Mark

  • Sweep

  • Compact

Unreachable objects are removed.


21. What are GC Generations?

Answer:

Heap divided into:

  • Young Generation

  • Old Generation

Young generation collected frequently (Minor GC).

Old generation collected less frequently (Major/Full GC).


22. What is Minor GC?

Answer:

Occurs in Young Generation.

  • Fast

  • Moves surviving objects to Survivor or Old generation


23. What is Major GC / Full GC?

Answer:

Occurs in Old Generation.

  • Slower

  • Causes longer pause

  • Cleans entire heap


24. What are different Garbage Collectors?

Answer:

  • Serial GC

  • Parallel GC

  • CMS (Deprecated)

  • G1 GC

  • ZGC

  • Shenandoah GC

G1 is default in modern Java versions.


25. What is Stop-The-World?

Answer:

During GC, application threads are paused.

This pause is called Stop-The-World.


26. What is Memory Leak in Java?

Answer:

Memory leak occurs when:

  • Objects are no longer used

  • But still referenced

So GC cannot remove them.

Common causes:

  • Static collections

  • Unclosed resources

  • Listeners not removed


27. What is OutOfMemoryError?

Answer:

Occurs when JVM cannot allocate memory.

Common types:

  • Java heap space

  • Metaspace

  • GC overhead limit exceeded


28. Difference between G1 and ZGC

G1ZGC
Region-basedRegion-based
Stop-the-worldVery low pause
Good for medium-large heapLarge heap
Moderate latencyUltra-low latency

29. How to tune JVM for high traffic application?

Key parameters:

-Xms 4g
-Xmx 4g
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200

Tuning focus:

  • Proper heap sizing

  • Avoid frequent GC

  • Choose correct GC

  • Monitor with JFR

Strong Interview Closing Line

JVM Internals include:

  • Class loading mechanism

  • Memory structure (Heap, Stack, Metaspace)

  • Java Memory Model

  • Garbage collection strategies

  • Performance tuning


1️⃣6️⃣ Reflection API


1. What is Reflection in Java?

Answer:

Reflection is a feature that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime.

Located in:

  • java.lang.reflect package

Used to:

  • Inspect class structure

  • Access private members

  • Create objects dynamically

  • Invoke methods at runtime

Interview Line:

Reflection allows runtime inspection and modification of class behavior.


2. How to get Class object in Java?

Answer:

There are three ways:

Using .class

Class<?> cls = String.class;

Using getClass()

String str = "Java";
Class<?> cls = str.getClass();

Using Class.forName()

Class<?> cls = Class.forName("java.lang.String");

3. How to get Constructors using Reflection?

Answer:

Class<?> cls = Class.forName("java.lang.String");

Constructor<?>[] constructors =
cls.getConstructors();

To get specific constructor:

Constructor<?> constructor =
cls.getConstructor(String.class);

To create object dynamically:

Object obj = constructor.newInstance("Hello");

4. How to get Methods using Reflection?

Answer:

Method[] methods = cls.getMethods();

To get specific method:

Method method =
cls.getMethod("length");

To invoke method:

Object result = method.invoke("Java");

5. How to access private methods using Reflection?

Answer:

Method method =
cls.getDeclaredMethod("privateMethod");

method.setAccessible(true);
method.invoke(object);

Used carefully as it breaks encapsulation.


6. How to get Fields using Reflection?

Answer:

Field[] fields = cls.getDeclaredFields();

To access private field:

Field field =
cls.getDeclaredField("name");

field.setAccessible(true);
field.set(object, "New Value");

7. What is setAccessible(true)?

Answer:

Used to bypass access control checks.

Allows access to:

  • Private fields

  • Private methods

  • Private constructors

Not recommended in normal application code.


8. What are real-time uses of Reflection?

Answer:

Used in:

  • Spring Framework

  • Hibernate

  • Dependency Injection

  • JUnit

  • Serialization

  • Annotations processing

Example:

Spring uses reflection to inject dependencies.


9. What are advantages of Reflection?

Answer:

  • Dynamic behavior

  • Framework development

  • Flexible architecture

  • Runtime inspection


10. What are disadvantages of Reflection?

Answer:

  • Slower performance

  • Breaks encapsulation

  • Security risks

  • Harder to maintain

  • Less compile-time checking


11. What is the difference between getMethod() and getDeclaredMethod()?

Answer:

getMethod()

  • Returns public methods

  • Includes inherited methods

getDeclaredMethod()

  • Returns all methods of class

  • Includes private methods

  • Does not include inherited methods


12. What is the difference between Class.newInstance() and Constructor.newInstance()?

Answer:

Class.newInstance()

  • Deprecated

  • Only calls no-arg constructor

Constructor.newInstance()

  • Can call any constructor

  • More flexible

  • Recommended approach


13. What is Reflection used for in Spring?

Answer:

Spring uses Reflection for:

  • Dependency Injection

  • Creating beans

  • Calling lifecycle methods

  • Processing annotations

  • Proxy creation


Frequently Asked Interview Questions

Can we modify private field using reflection?

Is reflection slow? Why?

Is reflection secure?

Where is reflection heavily used?


Strong Interview Closing Line

Reflection enables:

  • Runtime inspection

  • Dynamic object creation

  • Framework-level programming

It is powerful but should be used carefully due to performance and security concerns.


1️⃣7️⃣ Annotations


1. What is an Annotation in Java?

Answer:

Annotation is a metadata that provides information about code.

  • Does not change program logic

  • Used by compiler or frameworks

  • Introduced in Java 5

Used for:

  • Configuration

  • Documentation

  • Code analysis

  • Runtime processing

Interview Line:

Annotations provide metadata about code that can be processed at compile-time or runtime.


2. What are Built-in Annotations in Java?

Answer:

Common built-in annotations:

  • @Override

  • @Deprecated

  • @SuppressWarnings

  • @FunctionalInterface

  • @SafeVarargs

@Override

Indicates method is overriding superclass method.

  • Helps avoid mistakes

  • Compile-time checking

@Deprecated

Marks method/class as deprecated.

  • Shows warning during compilation

  • Suggests not to use it

@SuppressWarnings

Suppresses compiler warnings.

Example:

@SuppressWarnings("unchecked")

@FunctionalInterface

Ensures interface has only one abstract method.


3. What are Meta-Annotations?

Answer:

Meta-annotations are annotations applied to other annotations.

Common meta-annotations:

  • @Retention

  • @Target

  • @Documented

  • @Inherited

  • @Repeatable


4. What is @Retention?

Answer:

Defines how long annotation is retained.

Retention policies:

  • SOURCE

  • CLASS

  • RUNTIM

Example:

@Retention(RetentionPolicy.RUNTIME)

RUNTIME means accessible via reflection


5. What is @Target?

Answer:

Specifies where annotation can be applied.

Common targets:

  • TYPE

  • METHOD

  • FIELD

  • CONSTRUCTOR

  • PARAMETER

Example:

@Target(ElementType.METHOD)

6. What is @Documented?

Answer:

Indicates annotation should be included in Javadoc.


7. What is @Inherited?

Answer:

Indicates annotation is inherited by subclasses.

Only applies to class-level annotations.


8. What is @Repeatable?

Answer:

Allows annotation to be applied multiple times on same element.


9. How to create a Custom Annotation?

Answer:

Syntax:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {
String value();
}

Using annotation:

@MyAnnotation("Test")
class Demo {
}

10. How to read Annotation using Reflection?

Answer:

Class<?> cls = Demo.class;

if (cls.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation =
cls.getAnnotation(MyAnnotation.class);

System.out.println(annotation.value());
}

Used in:

  • Spring

  • Hibernate

  • JUnit


11. What are Annotation Elements?

Answer:

Annotation can have elements (like methods).

Example:

@interface Author {
String name();
int version() default 1;
}

Used as:

@Author(name = "Siraj", version = 2)

12. What is the difference between Marker and Single-value Annotation?

Answer:

Marker Annotation:

  • No elements
    Example:

@interface Marker { }

Single-value Annotation:

  • One element

Example:

@interface Info {
String value();
}

13. What is Runtime vs Compile-time Annotation?

Answer:

Compile-time annotation:

  • Processed by compiler

  • Example: @Override

Runtime annotation:

  • Available via reflection

  • Requires RetentionPolicy.RUNTIME


14. Real-time use of Annotations

Answer:

Used in:

  • Spring (@Autowired, @Component)

  • Hibernate (@Entity, @Id)

  • JUnit (@Test)

  • REST APIs (@GetMapping)

  • Dependency Injection

Annotations make frameworks powerful and configuration-based.


Frequently Asked Interview Questions

What is difference between @Retention SOURCE and RUNTIME?

Can we create custom annotation?

How does Spring use annotations internally?

What is default retention policy? (CLASS)


Strong Interview Closing Line

Annotations provide:

  • Metadata-driven programming

  • Cleaner configuration

  • Framework-level automation

  • Compile-time and runtime processing