Core Java Interview Questions and Answers (2026)

Preparing for a Java developer interview? This guide covers 150+ Core Java interview questions with detailed answers — from beginner to advanced level — to help you crack rounds at TCS, Infosys, Wipro, Cognizant, Accenture, Goldman Sachs, JP Morgan, and product startups.

Whether you are a fresher applying for your first Java role or an experienced developer targeting senior positions, these questions cover what interviewers actually ask: OOP principles, collections internals, multithreading, Java 8 features, JVM memory model, exception handling, generics, and design patterns.

Topics covered:

  • Basic Java — JDK vs JRE vs JVM, platform independence, String pool, wrapper classes, pass-by-value
  • Object-Oriented Programming — inheritance, polymorphism, abstraction, encapsulation, interfaces
  • Exception Handling — checked vs unchecked, try-with-resources, custom exceptions, propagation
  • Collections Framework — ArrayList vs LinkedList, HashMap internals, fail-fast, Comparable vs Comparator
  • Multithreading — thread lifecycle, synchronization, deadlock, volatile, thread pool, Callable
  • Java 8+ Features — lambdas, Stream API, Optional, functional interfaces, method references, Date/Time API
  • JVM and Memory — heap vs stack, garbage collection, GC algorithms, memory leaks, reference types
  • Advanced Topics — reflection, generics, annotations, ClassLoader, serialization, design patterns

Who this is for: Java freshers (0-2 years), mid-level developers (2-5 years), and senior engineers preparing for full-stack or backend-focused rounds.

1. Basic Java Concepts

Q1. What is Java and what are its main features?

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle) in 1995. It follows the principle "Write Once, Run Anywhere" (WORA).

Key features:

  • Platform independent — Java compiles to bytecode that runs on any JVM
  • Object-oriented — everything modelled as objects with encapsulation, inheritance, polymorphism
  • Strongly typed — all variables must be declared with a data type
  • Automatic memory management — garbage collector handles deallocation
  • Multithreaded — built-in support for concurrent programming
  • Robust — strong type checking, exception handling, no pointer arithmetic
  • Secure — bytecode verifier, no direct memory access
  • Distributed — supports RMI, sockets, and web services natively

Q2. Explain the difference between JDK, JRE, and JVM.

ComponentFull FormContentsWho needs it
JVMJava Virtual MachineBytecode interpreter, JIT compiler, GC, memory managerRuntime — embedded inside JRE
JREJava Runtime EnvironmentJVM + core class libraries (java.lang, java.util)End users running Java apps
JDKJava Development KitJRE + compiler (javac) + debugger (jdb) + tools (javadoc, jar)Developers writing and compiling Java

In short: JDK contains JRE, which contains JVM.


Q3. What is platform independence in Java?

Java achieves platform independence through its two-step compilation model:

  1. The Java compiler (javac) converts .java source code into bytecode (.class files)
  2. The JVM on each OS interprets and executes that bytecode using a JIT (Just-In-Time) compiler

Since every OS has its own JVM implementation, the same .class file runs on Windows, Linux, and macOS without recompilation — this is "Write Once, Run Anywhere."


Q4. Is Java pass-by-value or pass-by-reference?

Java is strictly pass-by-value — always. For objects, the value passed is a copy of the reference (memory address), not the object itself.

void changeValue(int x) { x = 100; }     // primitive — caller unaffected
void changeName(Person p) { p.name = "Bob"; } // modifies the object — visible to caller
void reassign(Person p) { p = new Person(); } // reassign — caller unaffected

Q5. What is a constructor? What are its types?

A constructor has the same name as the class, no return type, and is called automatically when an object is created with new.

Types:

1. Default (no-arg) constructor — compiler provides one if none is defined.

2. Parameterised constructor:

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

3. Copy constructor (must write manually in Java):

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

Constructor chaining: Use this() to call another constructor in the same class, or super() to call the parent constructor. Both must be the first statement.


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

KeywordContextPurpose
finalVariable, method, or classVariable: cannot be reassigned. Method: cannot be overridden. Class: cannot be subclassed.
finallytry-catch blockAlways executes after try/catch — used for cleanup (closing streams, connections)
finalize()Method in Object classCalled by GC before collecting an object. Deprecated since Java 9 — use try-with-resources instead

Q7. What is the difference between throw and throws?

throwthrows
PurposeActually throws an exception instanceDeclares that a method may throw an exception
LocationInside method bodyIn the method signature
Examplethrow new IOException("not found")void read() throws IOException

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

==.equals()
ComparesReference (memory address)Content/value (depends on override)
PrimitivesCompares actual valuesNot applicable
Objectstrue only if same object in memorytrue if content is logically equal
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b);       // false — different objects
System.out.println(a.equals(b));  // true  — same content

Q9. What is the difference between String, StringBuilder, and StringBuffer?

StringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-safeYes (immutable)NoYes (synchronized)
PerformanceSlow for concatenationFastestSlower than StringBuilder
Use whenValue doesn't changeSingle-threaded string buildingMulti-threaded string building

Q10. Why is String immutable in Java?

Strings are stored as private final char[] (or byte[] in Java 9+) with no methods that modify the array after construction.

Benefits:

  1. String pool efficiency — multiple variables safely share the same literal
  2. Security — passwords and file paths cannot be altered after passing
  3. Thread safety — immutable objects can be shared across threads without synchronization
  4. Hashcode caching — hash computed once and cached; makes Strings efficient HashMap keys

Q11. What is the String pool?

The String pool is a special heap area where the JVM stores string literals to avoid duplicate objects.

String a = "hello";              // stored in pool
String b = "hello";              // reuses same pool entry
String c = new String("hello");  // new object on heap, NOT in pool

System.out.println(a == b);           // true  — same pool reference
System.out.println(a == c);           // false — c is on heap
System.out.println(a == c.intern());  // true  — intern() brings c into pool

Q12. What are wrapper classes and autoboxing?

Wrapper classes wrap primitive types into objects for use in collections and generics.

PrimitiveWrapperPrimitiveWrapper
intIntegerfloatFloat
longLongbooleanBoolean
doubleDoublecharCharacter

Autoboxing/Unboxing — Java automatically converts between primitives and wrappers:

Integer x = 5;      // autoboxing: int to Integer
int y = x;          // unboxing: Integer to int
list.add(10);       // autoboxing happens automatically

Q13. What is the difference between stack and heap memory?

StackHeap
StoresMethod call frames, local variables, referencesAll objects and instance variables
ScopeEach thread has its own stackShared across all threads
SizeSmall (512KB-2MB per thread)Large (configured via -Xmx)
AllocationLIFO — auto on method enter/exitDynamic — GC reclaims unreachable objects
ErrorStackOverflowErrorOutOfMemoryError

Q14. What is the difference between shallow copy and deep copy?

Shallow copy copies field values. For reference fields, it copies the reference — both copies point to the same nested object.

Deep copy recursively copies all nested objects so the copy is fully independent.

class Address { String city; }
class Person implements Cloneable {
    String name;
    Address address;

    // Shallow — address reference shared between original and copy
    public Person shallowCopy() throws CloneNotSupportedException {
        return (Person) super.clone();
    }

    // Deep — fully independent
    public Person deepCopy() throws CloneNotSupportedException {
        Person copy = (Person) super.clone();
        copy.address = new Address();
        copy.address.city = this.address.city;
        return copy;
    }
}

2. Object-Oriented Programming

Q15. What are the four pillars of OOP?

PillarDefinitionJava example
EncapsulationBundling data and methods; hiding internal state via access modifiersprivate fields + public getters/setters
InheritanceA child class acquires properties and behaviours of a parent classclass Dog extends Animal
PolymorphismOne interface, many implementationsMethod overriding, method overloading
AbstractionHiding implementation details, exposing only what is necessaryabstract class, interface

Q16. Why doesn't Java support multiple inheritance through classes?

Java avoids the Diamond Problem: if class C inherits from both A and B, and both have the same method display(), which version does C inherit? This ambiguity could cause unpredictable behaviour.

Java's solution:

  • Classes: single inheritance only (extends one class)
  • Interfaces: multiple implementation allowed (implements A, B, C) — default method conflicts must be explicitly resolved
interface A { default void greet() { System.out.println("A"); } }
interface B { default void greet() { System.out.println("B"); } }
class C implements A, B {
    public void greet() { A.super.greet(); } // must resolve explicitly
}

Q17. What is the difference between method overloading and overriding?

OverloadingOverriding
DefinitionSame method name, different parameters in the SAME classSame method name and parameters in PARENT and CHILD class
Polymorphism typeCompile-time (static)Runtime (dynamic)
Return typeCan differMust be same or covariant
Access modifierCan be anythingCannot be more restrictive than parent

Q18. What is the difference between abstract class and interface?

Abstract ClassInterface
MethodsAbstract + concrete methodsAbstract; default/static allowed (Java 8+)
VariablesAny type of fieldspublic static final constants only
ConstructorCan have constructorsCannot have constructors
InheritanceSingle inheritance (extends one)Multiple implementation (implements many)
Use whenShared code/state among related classesContract/capability across unrelated classes

Q19. What is composition vs inheritance? Which is preferred?

  • Inheritance — "is-a" relationship: Dog extends Animal
  • Composition — "has-a" relationship: Car has Engine
// Composition (preferred)
class Engine { void start() {} }
class Car {
    private Engine engine = new Engine(); // Car HAS-A Engine
    void startCar() { engine.start(); }
}

Prefer composition because it gives looser coupling, avoids the fragile base class problem, and is more flexible at runtime.


Q20. What is the Singleton pattern? How to make it thread-safe?

Singleton ensures only one instance of a class exists.

Thread-safe double-checked locking:

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) instance = new Singleton();
            }
        }
        return instance;
    }
}

Best practice — Enum Singleton:

public enum Singleton { INSTANCE; }

Thread-safe, serialization-safe, and reflection-proof by default.


Q21. What is runtime polymorphism?

Runtime polymorphism (dynamic dispatch) — the method to be called is resolved at runtime based on the actual object type, not the reference type.

class Animal { void sound() { System.out.println("..."); } }
class Dog extends Animal { void sound() { System.out.println("Woof"); } }
class Cat extends Animal { void sound() { System.out.println("Meow"); } }

Animal a = new Dog(); // upcasting
a.sound(); // "Woof" — resolved at runtime

3. Exception Handling

Q22. What is the Java exception hierarchy?

Throwable
├── Error               (JVM-level — do NOT catch: OutOfMemoryError, StackOverflowError)
└── Exception
    ├── RuntimeException  (unchecked — don't require try-catch)
    │   ├── NullPointerException
    │   ├── ArrayIndexOutOfBoundsException
    │   └── IllegalArgumentException
    └── Checked exceptions  (must declare or catch)
        ├── IOException
        ├── SQLException
        └── ClassNotFoundException

Q23. What is the difference between checked and unchecked exceptions?

CheckedUnchecked
Checked atCompile timeRuntime
ExtendsException (not RuntimeException)RuntimeException
Must handle?Yes — try-catch or throws requiredNo — optional
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException
CauseExternal factors (file not found, DB down)Programming bugs

Q24. What is try-with-resources?

Introduced in Java 7 — automatically closes any AutoCloseable resource when the try block exits.

// Java 7+ — automatic close
try (FileReader fr = new FileReader("file.txt");
     BufferedReader br = new BufferedReader(fr)) {
    String line = br.readLine();
} // fr and br closed automatically in reverse order

Q25. What is exception propagation?

When an exception is thrown and not caught in the current method, it propagates up the call stack to the caller, and so on, until caught or the JVM terminates.

void c() { throw new RuntimeException("Error"); }
void b() { c(); } // propagates up
void a() { b(); } // propagates up
public static void main(String[] args) {
    try { a(); }
    catch (RuntimeException e) { System.out.println("Caught: " + e.getMessage()); }
}

Q26. How do you create a custom exception?

// Custom checked exception
public class InsufficientFundsException extends Exception {
    private double shortfall;

    public InsufficientFundsException(double shortfall) {
        super("Insufficient funds. Short by: " + shortfall);
        this.shortfall = shortfall;
    }

    public double getShortfall() { return shortfall; }
}

// Usage
public void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) throw new InsufficientFundsException(amount - balance);
    balance -= amount;
}

Extend RuntimeException for unchecked custom exceptions.


4. Collections Framework

Q27. What is the Java Collections Framework?

The Java Collections Framework (JCF) provides interfaces, implementations, and algorithms for storing and manipulating groups of objects.

InterfaceDuplicatesOrderedCommon implementations
ListYesYes (by index)ArrayList, LinkedList, Vector
SetNoNo (HashSet) / Yes (LinkedHashSet, TreeSet)HashSet, LinkedHashSet, TreeSet
MapKeys: No, Values: YesNo (HashMap) / Yes (LinkedHashMap, TreeMap)HashMap, LinkedHashMap, TreeMap
QueueYesFIFOLinkedList, PriorityQueue, ArrayDeque

Q28. What is the difference between ArrayList and LinkedList?

ArrayListLinkedList
Internal structureDynamic array (Object[])Doubly-linked list of nodes
get(i) — random accessO(1)O(n) — must traverse
add/remove at endO(1) amortisedO(1)
add/remove in middleO(n) — shifts elementsO(1) after finding the node
MemoryLess overheadMore (prev/next pointers per node)
Use whenFrequent reads by indexFrequent insertions/deletions

Q29. How does HashMap work internally?

HashMap is backed by an array of buckets (Node[] table).

When you call put(key, value):

  1. Compute hashCode() of the key
  2. Apply secondary hash to get bucket index: index = hash & (capacity - 1)
  3. If bucket is empty — place the entry
  4. If collision — compare with equals():
    • Equal key: update value
    • Different key: add to linked list (or Red-Black tree if bucket size > 8, Java 8+)

Resize (rehash): When size > capacity x loadFactor (default 0.75), the array doubles.


Q30. What is the difference between HashMap and ConcurrentHashMap?

HashMapConcurrentHashMap
Thread-safeNoYes
LockingNoneBucket-level CAS (Java 8+)
Null keysOne null key allowedNo null keys or values
IterationFail-fast (ConcurrentModificationException)Weakly consistent — no exception

Q31. What is fail-fast vs fail-safe iteration?

Fail-fast (ArrayList, HashMap): throws ConcurrentModificationException if the collection is modified during iteration.

Fail-safe (CopyOnWriteArrayList, ConcurrentHashMap): iterates over a snapshot — no exception during concurrent modification.

// Fail-fast — throws ConcurrentModificationException
for (String s : list) { list.remove(s); } // ERROR

// Safe removal
Iterator<String> it = list.iterator();
while (it.hasNext()) { it.next(); it.remove(); } // OK

Q32. What is the difference between Comparable and Comparator?

ComparableComparator
Packagejava.langjava.util
MethodcompareTo(T o)compare(T o1, T o2)
Implemented inThe class itselfSeparate class or lambda
Use whenNatural/default orderingMultiple/custom orderings
// Comparable — natural order by marks
class Student implements Comparable<Student> {
    int marks;
    public int compareTo(Student s) { return this.marks - s.marks; }
}

// Comparator — sort by name
students.sort(Comparator.comparing(s -> s.name));

5. Multithreading

Q33. What are the different ways to create threads?

1. Implement Runnable (preferred):

Thread t = new Thread(() -> System.out.println("Running"));
t.start();

2. Extend Thread:

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

3. ExecutorService (recommended for production):

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> processTask());
pool.shutdown();

Q34. What are the thread lifecycle states?

StateDescription
NEWThread created but start() not called
RUNNABLEExecuting or ready to execute (waiting for CPU)
BLOCKEDWaiting to acquire a monitor lock
WAITINGWaiting indefinitely — wait(), join() with no timeout
TIMED_WAITINGWaiting for a specified time — sleep(ms), wait(ms)
TERMINATEDrun() has completed

Q35. What is synchronization? Why is it needed?

When multiple threads access shared mutable data, race conditions occur. Synchronization ensures only one thread executes a critical section at a time.

class Counter {
    private int count = 0;
    public synchronized void increment() { count++; } // method-level lock
    public void decrement() {
        synchronized(this) { count--; } // block-level (finer granularity)
    }
}

Q36. What is deadlock? How do you avoid it?

Deadlock: two threads permanently blocked, each waiting for a lock held by the other.

Thread 1: holds Lock A, waiting for Lock B
Thread 2: holds Lock B, waiting for Lock A  →  deadlock

Prevention:

  • Always acquire multiple locks in the same fixed order
  • Use tryLock() with timeout from java.util.concurrent.locks
  • Minimize scope of synchronized blocks
  • Prefer java.util.concurrent utilities over raw synchronized

Q37. What is the volatile keyword?

volatile ensures a variable is always read from and written to main memory — not a thread-local CPU cache. Guarantees visibility but NOT atomicity.

class Server {
    volatile boolean running = true;
    void stop() { running = false; }
    void serve() { while (running) { /* always reads latest value */ } }
}

For compound operations like count++, use AtomicInteger — not just volatile.


Q38. What is the difference between wait() and sleep()?

wait()sleep()
ClassObjectThread
Releases lock?YesNo — keeps the lock
Woken bynotify() or notifyAll()Time expiry or interrupt
Must be insynchronized blockAnywhere
PurposeInter-thread communicationPause execution for fixed time

Q39. What is the difference between Callable and Runnable?

RunnableCallable<V>
Methodvoid run()V call() throws Exception
Return valueNoneReturns V
Checked exceptionsCannot throwCan throw
Used withThread, ExecutorServiceExecutorService — returns Future<V>
Future<Integer> future = pool.submit(() -> { Thread.sleep(1000); return 42; });
System.out.println(future.get()); // blocks until done — prints 42

6. Java 8+ Features

Q40. What are lambda expressions?

A lambda is a concise anonymous function implementing a functional interface (one abstract method).

// Before Java 8
Runnable r = new Runnable() { public void run() { System.out.println("Hi"); } };

// Java 8 lambda
Runnable r = () -> System.out.println("Hi");

// With parameters
Comparator<String> comp = (a, b) -> a.compareTo(b);

Q41. What are functional interfaces?

A functional interface has exactly one abstract method. Built-in ones in java.util.function:

InterfaceMethodDescription
Predicate<T>boolean test(T t)Test a condition — returns true/false
Function<T,R>R apply(T t)Transform T to R
Consumer<T>void accept(T t)Consume T, no return
Supplier<T>T get()Supply a T, no input
BiFunction<T,U,R>R apply(T t, U u)Two inputs, one output

Q42. What is the Stream API?

Streams provide a declarative functional-style way to process collections. Operations are lazy — executed only when a terminal operation triggers the pipeline.

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

int result = numbers.stream()
    .filter(n -> n % 2 == 0)    // intermediate — lazy
    .map(n -> n * n)             // intermediate — lazy
    .reduce(0, Integer::sum);    // terminal — triggers execution

System.out.println(result); // 4 + 16 + 36 = 56

Streams don't modify the original collection and can only be consumed once.


Q43. What is the Optional class?

Optional<T> is a container that may or may not hold a non-null value — designed to eliminate NullPointerException.

Optional<String> name = Optional.of("Alice");
Optional<String> nullable = Optional.ofNullable(null);

name.isPresent();                          // true
name.get();                                // "Alice"
nullable.orElse("N/A");                    // "N/A"
name.map(String::toUpperCase).orElse(""); // "ALICE"
name.ifPresent(System.out::println);       // prints "Alice"

Use Optional as return types only — not as method parameters or class fields.


Q44. What is method reference?

Method references are shorthand for lambdas that call a single method:

TypeSyntaxExample
Static methodClass::staticMethodInteger::parseInt
Instance (specific object)object::instanceMethodSystem.out::println
Instance (arbitrary object)Class::instanceMethodString::toUpperCase
ConstructorClass::newArrayList::new

Q45. What is the difference between map() and flatMap()?

  • map() — transforms each element 1-to-1; result may be nested
  • flatMap() — transforms each element to a stream and flattens into one stream
List<List<Integer>> nested = Arrays.asList(
    Arrays.asList(1, 2), Arrays.asList(3, 4)
);

// flatMap — flattens to [1, 2, 3, 4]
nested.stream().flatMap(List::stream).collect(Collectors.toList());

7. JVM and Memory Management

Q46. How is JVM memory organised?

Memory areaContentsPer thread?
HeapAll objects (Young Gen + Old Gen)Shared
StackMethod frames, local variables, referencesPer thread
Metaspace (Java 8+)Class metadata (replaces PermGen)Shared
Code CacheJIT-compiled native codeShared
PC RegisterAddress of current instructionPer thread

Q47. What is garbage collection? How does generational GC work?

The Garbage Collector automatically removes objects no longer reachable, freeing heap memory.

Generational GC:

  • Young Generation (Eden + Survivor spaces): newly created objects — collected frequently (Minor GC, fast)
  • Old Generation: long-lived objects — collected infrequently (Major GC, slower)

GC algorithms:

GCBest forDefault?
Serial GCSmall, single-threaded appsNo
Parallel GCThroughput-focused multi-threadedJava 8 default
G1 GCLarge heaps, predictable pause timesJava 9+ default
ZGC / ShenandoahSub-millisecond pausesJava 11+ opt-in

Q48. What are the different types of references?

TypeGC behaviourUse case
StrongNot collected while reference existsAll normal objects
Soft (SoftReference)Collected only when memory is lowMemory-sensitive caches
Weak (WeakReference)Collected at next GC cycleWeakHashMap keys, canonicalized maps
Phantom (PhantomReference)Enqueued in ReferenceQueue after collectionPost-mortem cleanup actions

8. Advanced Concepts

Q49. What is reflection in Java?

Reflection lets a program inspect and manipulate classes, methods, fields, and constructors at runtime — even private ones.

Class<?> clazz = Class.forName("com.example.Person");

// Invoke a private method
Method m = clazz.getDeclaredMethod("secretMethod");
m.setAccessible(true);
m.invoke(instance);

// Get/set a private field
Field f = clazz.getDeclaredField("name");
f.setAccessible(true);
f.set(instance, "Bob");

Used by Spring/Hibernate for DI, JUnit for test discovery. Slower than direct calls — avoid in hot paths.


Q50. What are generics in Java?

Generics add type parameters to classes and methods, enabling type safety without casting.

// Without generics — ClassCastException risk
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

// With generics — type-safe, no cast needed
List<String> list = new ArrayList<>();
list.add("hello");
String s = list.get(0);

Bounded type parameters:

  • <T extends Number> — T must be Number or subtype (upper bound)
  • <T super Integer> — T must be Integer or supertype (lower bound)
  • <?> — unknown wildcard

Q51. What is serialization? What is serialVersionUID?

Serialization converts an object to a byte stream for saving or sending over a network.

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    transient String password; // NOT serialized
}

// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("p.dat"))) {
    oos.writeObject(person);
}

// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("p.dat"))) {
    Person p = (Person) ois.readObject();
}

If serialVersionUID doesn't match during deserialization (class changed), an InvalidClassException is thrown.


Q52. What is the difference between ClassNotFoundException and NoClassDefFoundError?

ClassNotFoundExceptionNoClassDefFoundError
TypeChecked ExceptionError (unchecked)
When thrownClass.forName() can't find the class at runtimeClass present at compile time but missing at runtime
RecoveryCan be caught and handledUsually fatal

Q53. What are annotations? How do you create a custom one?

Annotations are metadata added to code, processed at compile time or runtime by frameworks.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Benchmark {
    String description() default "";
}

// Usage
@Benchmark(description = "measures latency")
public void processOrder() { ... }

// Read at runtime
Method m = MyService.class.getMethod("processOrder");
Benchmark b = m.getAnnotation(Benchmark.class);
System.out.println(b.description());

9. Design Patterns

Q54. What is the Factory Pattern?

Factory Method defines an interface for creating objects, letting a factory decide which class to instantiate.

interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("Circle"); } }
class Rectangle implements Shape { public void draw() { System.out.println("Rectangle"); } }

class ShapeFactory {
    static Shape create(String type) {
        return switch (type) {
            case "circle" -> new Circle();
            case "rectangle" -> new Rectangle();
            default -> throw new IllegalArgumentException("Unknown: " + type);
        };
    }
}

Q55. What is the Builder Pattern?

Builder separates construction of complex objects from their representation — avoids telescoping constructors.

class User {
    private final String name;
    private final String email;
    private User(Builder b) { name = b.name; email = b.email; }

    static class Builder {
        String name, email;
        Builder name(String n) { name = n; return this; }
        Builder email(String e) { email = e; return this; }
        User build() { return new User(this); }
    }
}

User user = new User.Builder().name("Alice").email("alice@test.com").build();

Q56. What is the Observer Pattern?

Observer defines a one-to-many dependency: when the subject changes, all observers are notified.

interface Observer { void update(String event); }

class EventBus {
    private List<Observer> observers = new ArrayList<>();
    void subscribe(Observer o) { observers.add(o); }
    void publish(String event) { observers.forEach(o -> o.update(event)); }
}

EventBus bus = new EventBus();
bus.subscribe(e -> System.out.println("Logger: " + e));
bus.subscribe(e -> System.out.println("Email: " + e));
bus.publish("USER_SIGNUP");

10. JDBC and Miscellaneous

Q57. What is JDBC? What are the key interfaces?

JDBC (Java Database Connectivity) is the standard API for connecting Java apps to relational databases.

try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
     PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
    ps.setInt(1, 42);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) { System.out.println(rs.getString("name")); }
}

Key interfaces: Connection, Statement, PreparedStatement, ResultSet, CallableStatement


Q58. What is the difference between Statement and PreparedStatement?

StatementPreparedStatement
SQL compilationCompiled on every executeCompiled once, reused
PerformanceSlower for repeated queriesFaster — DB caches execution plan
SQL injectionVulnerableSafe — parameters are escaped
Use whenDynamic SQL, no parametersParameterised or repeated queries

Q59. What is the transient keyword?

transient marks a field to be excluded from serialization. Transient fields are set to default values on deserialization.

class User implements Serializable {
    String username;
    transient String password;  // security-sensitive — not serialized
    transient Connection conn;  // cannot serialize a live DB connection
}

Q60. What is the difference between HashMap and Hashtable?

HashMapHashtable
Thread-safeNoYes (synchronized)
Null keys/valuesOne null key, multiple null valuesNo null keys or values
PerformanceFasterSlower (synchronization overhead)
StatusPreferredLegacy — use ConcurrentHashMap instead

Q61. What is connection pooling? Why is it important?

Connection pooling maintains a cache of pre-opened database connections that are reused instead of creating a new one per request.

Creating a DB connection is expensive (~50-200ms). A pool dramatically reduces latency and prevents resource exhaustion.

Popular pools: HikariCP (fastest, default in Spring Boot), Apache DBCP, c3p0

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost/mydb");
config.setMaximumPoolSize(20);
HikariDataSource ds = new HikariDataSource(config);
Connection conn = ds.getConnection(); // borrowed from pool, returned on close

Q62. What is a marker interface?

A marker interface is an interface with no methods or fields — it just marks a class to indicate it has a certain capability or property. The JVM or framework checks instanceof to decide behaviour.

Examples:

  • Serializable — marks a class as serializable
  • Cloneable — marks a class as supporting clone()
  • RandomAccess — signals that a List supports fast random access
class Person implements Serializable {} // marked — JVM will serialize it

if (obj instanceof Serializable) {
    // safe to serialize
}

Java 5+ annotations (@Entity, @FunctionalInterface) are the modern replacement for marker interfaces.


Q63. What is the difference between int and Integer?

intInteger
TypePrimitiveObject (wrapper class)
Default value0null
Memory4 bytes on stack16+ bytes on heap
CollectionsCannot be used (no generics with primitives)Can be stored in List<Integer>
NullCannot be nullCan be null (NullPointerException risk on unboxing)

Integer cache: Java caches Integer objects from -128 to 127. Comparing cached values with == gives true; outside that range it's false:

Integer a = 100, b = 100; System.out.println(a == b); // true (cached)
Integer c = 200, d = 200; System.out.println(c == d); // false (not cached)

Q64. What is type casting in Java?

Widening (implicit): smaller type to larger type — no data loss, done automatically.

int i = 10;
long l = i;   // int → long, automatic
double d = l; // long → double, automatic

Narrowing (explicit): larger type to smaller type — may lose data, requires explicit cast.

double d = 9.99;
int i = (int) d; // 9 — decimal part lost

Object casting:

Animal a = new Dog(); // upcasting — implicit
Dog d = (Dog) a;      // downcasting — explicit, may throw ClassCastException
if (a instanceof Dog) { Dog d = (Dog) a; } // safe downcasting

Q65. What are the different types of loops in Java?

1. for loop — when the number of iterations is known:

for (int i = 0; i < 5; i++) { System.out.println(i); }

2. while loop — when the condition is checked before each iteration:

int i = 0;
while (i < 5) { System.out.println(i++); }

3. do-while loop — executes at least once; condition checked after:

int i = 0;
do { System.out.println(i++); } while (i < 5);

4. enhanced for-each loop — iterates over arrays/Iterable collections:

int[] arr = {1, 2, 3};
for (int n : arr) { System.out.println(n); }

Q66. What are access modifiers in Java?

ModifierSame classSame packageSubclass (other package)Other packages
privateYesNoNoNo
(default)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Q67. What is the static keyword in Java?

static members belong to the class rather than any specific instance.

  • Static variable — shared across all instances; one copy per class
  • Static method — can be called without creating an object; cannot access instance fields
  • Static block — executed once when the class is loaded; used for static initialization
  • Static nested class — inner class that doesn't need an outer class instance
class MathUtil {
    static final double PI = 3.14159;  // static constant

    static double circleArea(double r) { return PI * r * r; } // static method
}

double area = MathUtil.circleArea(5); // no object needed

11. File I/O and Serialization

Q68. What is the difference between FileInputStream and FileReader?

FileInputStreamFileReader
ReadsRaw bytesCharacters (text)
Use forBinary files (images, audio, PDFs)Text files (.txt, .csv, .json)
EncodingNo encoding — raw bytesUses platform/specified charset
ExtendsInputStreamReader (InputStreamReader)

For text files, wrap in BufferedReader for efficiency:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) { System.out.println(line); }
}

Q69. What is the difference between Reader/Writer and InputStream/OutputStream?

InputStream / OutputStreamReader / Writer
Data unitByte (8-bit)Character (16-bit Unicode)
Best forBinary dataText data
Key classesFileInputStream, FileOutputStream, BufferedInputStreamFileReader, FileWriter, BufferedReader, PrintWriter

Q70. What is externalization in Java?

Externalization (Externalizable interface) gives full control over serialization — you implement writeExternal() and readExternal() to define exactly what gets serialized.

class Config implements Externalizable {
    String host;
    int port;

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(host);
        out.writeInt(port);
    }

    public void readExternal(ObjectInput in) throws IOException {
        host = in.readUTF();
        port = in.readInt();
    }
}

Serializable vs Externalizable:

  • Serializable — JVM handles everything automatically (via reflection); slower
  • Externalizable — you control exactly what is written; faster, more compact

Q71. What is NIO (New I/O) in Java?

Java NIO (java.nio) provides buffer-oriented, optionally non-blocking I/O.

Classic I/O (java.io)NIO (java.nio)
ModelStream-orientedBuffer-oriented
BlockingAlways blockingCan be non-blocking (Channels + Selectors)
File APIFile classPath, Paths, Files classes
// NIO Path API
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
Files.write(path, "Hello".getBytes());
long size = Files.size(path);

Q72. What is memory-mapped file I/O?

Memory-mapped I/O (FileChannel.map()) maps a file directly into the JVM's virtual memory. The OS handles loading pages from disk on demand — extremely fast for large files since there's no explicit read/write call.

try (FileChannel fc = FileChannel.open(Paths.get("large.dat"), StandardOpenOption.READ)) {
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    byte firstByte = buffer.get(0); // direct memory access
}

Used in databases, log processors, and high-performance I/O scenarios.


12. Multithreading — Advanced

Q73. What is thread starvation?

Thread starvation occurs when a thread never gets CPU time because other higher-priority threads always preempt it, or a lock is always held by other threads.

Common causes:

  • Threads with higher priority continuously executing
  • A synchronized block held too long by one thread
  • Unfair locking (threads don't get equal turns)

Solution: Use ReentrantLock with fairness = true:

Lock lock = new ReentrantLock(true); // fair lock — threads served in FIFO order

Q74. What is the difference between notify() and notifyAll()?

Both methods wake threads that are in wait() on the same object's monitor.

  • notify() — wakes one arbitrary waiting thread (non-deterministic which one)
  • notifyAll() — wakes all waiting threads; they compete for the lock
synchronized(obj) {
    obj.notify();     // wake one
    obj.notifyAll();  // wake all
}

Use notifyAll() by default — using notify() can lead to missed signals if the wrong thread is woken.


Q75. What is the difference between yield() and join()?

yield()join()
PurposeHints the scheduler to give CPU to other threads of same/higher priorityCurrent thread waits for the specified thread to finish
GuaranteeNo guarantee — scheduler may ignore the hintGuaranteed — current thread blocks until target thread terminates
Called onThread.yield() — static, affects current threadthread.join() — instance method

Q76. What is the difference between synchronized method and synchronized block?

Synchronized method — locks the entire method on this (or the class object for static methods):

public synchronized void increment() { count++; } // locks 'this' for entire method

Synchronized block — locks only a specific section on a specified object:

public void increment() {
    synchronized(this) { count++; } // locks only this block
    // rest of method runs without lock
}

Prefer synchronized blocks — they have finer granularity, reducing contention and improving throughput.


13. Java 8 — Advanced Features

Q77. What is the purpose of Collectors in Java 8?

Collectors is a utility class providing built-in collector implementations for the collect() terminal operation:

List<String> names = Arrays.asList("Alice", "Bob", "Alice", "Charlie");

// Collect to List
List<String> list = names.stream().collect(Collectors.toList());

// Collect to Set (removes duplicates)
Set<String> set = names.stream().collect(Collectors.toSet());

// Join to String
String joined = names.stream().collect(Collectors.joining(", ")); // "Alice, Bob, Alice, Charlie"

// Group by length
Map<Integer, List<String>> byLength = names.stream()
    .collect(Collectors.groupingBy(String::length));

// Count occurrences
Map<String, Long> counts = names.stream()
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

Q78. What is the difference between Predicate and Function?

Predicate<T>Function<T, R>
ReturnsbooleanAny type R
Methodtest(T t)apply(T t)
Used forFiltering — stream.filter(predicate)Transformation — stream.map(function)
Composingand(), or(), negate()andThen(), compose()
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;
Predicate<Integer> isEvenAndPositive = isEven.and(isPositive);

Function<String, Integer> toLength = String::length;
Function<Integer, String> toStr = n -> "Length: " + n;
Function<String, String> composed = toLength.andThen(toStr);
System.out.println(composed.apply("hello")); // "Length: 5"

Q79. What are default methods in interfaces? Why were they introduced?

Default methods (Java 8+) are concrete methods in interfaces. They were introduced primarily for backward compatibility — adding new methods to existing interfaces without breaking all implementing classes.

interface Collection {
    // New method added in Java 8 — all existing implementations inherit this
    default void forEach(Consumer<? super E> action) {
        for (E e : this) action.accept(e);
    }
}

If two interfaces provide conflicting default methods, the implementing class must override and resolve the conflict:

interface A { default void greet() { System.out.println("A"); } }
interface B { default void greet() { System.out.println("B"); } }
class C implements A, B {
    public void greet() { A.super.greet(); } // explicit resolution required
}

Q80. What is the new Date/Time API in Java 8?

The legacy java.util.Date and Calendar were mutable, not thread-safe, and poorly designed. Java 8 introduced java.time:

ClassPurposeExample
LocalDateDate without timeLocalDate.now() → 2026-05-28
LocalTimeTime without dateLocalTime.of(14, 30)
LocalDateTimeDate and timeLocalDateTime.now()
ZonedDateTimeDate and time with timezoneZonedDateTime.now(ZoneId.of("Asia/Kolkata"))
InstantMachine timestampInstant.now()
Duration / PeriodTime/date spansChronoUnit.DAYS.between(d1, d2)

All java.time classes are immutable and thread-safe.


14. Memory Management — Advanced

Q81. What causes memory leaks in Java?

Although Java has a GC, memory leaks can still occur when objects are unintentionally kept reachable:

  • Static collections holding references to large objects that are never removed
  • Listeners/callbacks not removed after use (common in GUI applications)
  • ThreadLocal variables not cleaned up in thread pools
  • Inner class instances holding a reference to the outer class
  • Unclosed streams and connections (before Java 7's try-with-resources)
  • String interning abuse — calling .intern() on large/dynamic strings fills the pool

Detection tools: JVisualVM, Eclipse MAT (Memory Analyzer), JProfiler, -XX:+HeapDumpOnOutOfMemoryError


Q82. What is the difference between Minor GC and Major GC?

Minor GCMajor (Full) GC
CollectsYoung Generation (Eden + Survivor)Old Generation (and sometimes entire heap)
FrequencyFrequentInfrequent
Pause timeShort (milliseconds)Longer (may cause noticeable pauses)
TriggersEden space fills upOld Gen fills up or explicit System.gc()

Q83. What is System.gc()? Should you call it?

System.gc() is a hint to the JVM to run garbage collection. It does NOT guarantee that GC will run — the JVM may ignore it.

Should you call it? Almost never in production code:

  • GC pauses block your application
  • The JVM's GC algorithms are already well-tuned
  • Calling it can actually hurt performance by triggering a Full GC unnecessarily

Legitimate use: in memory benchmarks or teardown of tests.


15. Servlets and Web Basics

Q84. What is a servlet?

A servlet is a Java class that handles HTTP requests and generates responses, running inside a servlet container (Tomcat, Jetty).

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        res.setContentType("text/html");
        res.getWriter().println("<h1>Hello World</h1>");
    }
}

Servlet lifecycle: init()service() (called per request) → destroy()

Modern Java web development uses Spring MVC/Spring Boot which abstract servlets entirely.


Q85. What is the difference between forward and redirect in servlets?

Forward (server-side)Redirect (client-side)
HTTP round trips1 — handled internally on server2 — server sends 302, client makes new request
URL in browserUnchanged (original URL)Changes to new URL
Request attributesShared — same HttpServletRequestNew request — attributes lost
Use whenPassing data to another page internallyAfter form submit (PRG pattern) to prevent re-submission

Q86. What are cookies and sessions?

Cookie — a small piece of data stored on the client (browser). Sent with every HTTP request to the same domain. Used for preferences, authentication tokens.

Cookie cookie = new Cookie("username", "alice");
cookie.setMaxAge(86400); // 1 day
response.addCookie(cookie);

Session — server-side storage identified by a session ID (stored in a cookie named JSESSIONID). More secure since data stays on the server.

HttpSession session = request.getSession();
session.setAttribute("cart", cartObject);
Cart cart = (Cart) session.getAttribute("cart");

Difference: Cookies store data on the client; sessions store data on the server.


Q87. What is JDBC connection pooling?

A connection pool keeps a set of pre-opened database connections ready for reuse. Creating a new DB connection (~50-200ms) for every request is too expensive.

HikariCP (fastest, default in Spring Boot):

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("root");
config.setPassword("pass");
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
DataSource ds = new HikariDataSource(config);

Pool lends a connection on getConnection() and returns it to the pool when conn.close() is called — the connection is NOT actually closed.


Q88. What is the difference between GET and POST?

GETPOST
Data inURL query string (?name=Alice)Request body
SecurityVisible in URL/logs — not for sensitive dataNot in URL — more secure for passwords
IdempotentYes — repeated calls return same resultNo — repeated submissions create duplicate records
CacheableYesNo (by default)
Data sizeLimited (~2KB URL limit)No practical limit

Q89. What is the MVC pattern?

Model-View-Controller (MVC) separates an application into three components:

  • Model — business logic and data (POJO, database entities)
  • View — presentation layer (JSP, Thymeleaf, React)
  • Controller — handles user requests, coordinates Model and View (Servlet, Spring @Controller)
// Controller
@Controller
public class UserController {
    @GetMapping("/users/{id}")
    public String getUser(@PathVariable Long id, Model model) {
        User user = userService.findById(id); // Model
        model.addAttribute("user", user);
        return "user-profile"; // View name
    }
}

Benefits: Separation of concerns — changes to UI don't affect business logic and vice versa.


Q90. What are Java Beans?

A Java Bean is a plain Java class that follows a specific convention:

  • Private fields
  • Public no-arg constructor
  • Public getters (getXxx()) and setters (setXxx()) for each field
  • Implements Serializable (optional but recommended)
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public Person() {} // no-arg constructor required

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

Java Beans are used heavily in JSP/EL, Spring (as beans managed by the IoC container), and JPA entities.


16. Collections — Advanced

Q91. What is the difference between HashSet and TreeSet?

HashSetTreeSet
Internal structureHashMap (hash table)TreeMap (Red-Black Tree)
OrderingNo ordering guaranteedNatural order (or Comparator)
PerformanceO(1) add/remove/containsO(log n) — tree traversal
Null elementsOne null allowedNo null (comparison would throw NPE)
Use whenFast lookup, no order neededSorted unique elements needed

Q92. What is the load factor in HashMap?

The load factor determines when the HashMap resizes its internal array. Default is 0.75.

Resize threshold = capacity × loadFactor
Default: 16 × 0.75 = 12 → resize to 32 when 12 entries are added

Tradeoff:

  • Lower load factor (e.g. 0.5) — fewer collisions, faster lookups, but more memory and more frequent resizes
  • Higher load factor (e.g. 0.9) — less memory, but more collisions degrade to O(n) lookups

The default 0.75 is a good balance between time and space.


Q93. What is the difference between Vector and ArrayList?

ArrayListVector
Thread-safeNoYes (synchronized methods)
PerformanceFaster (no synchronisation)Slower
GrowthGrows by 50% when fullDoubles in size when full
LegacyJava 1.2 (Collections Framework)Java 1.0 (legacy)
Prefer insteadDefault choiceUse Collections.synchronizedList() or CopyOnWriteArrayList

Q94. How to make a collection read-only?

Use Collections.unmodifiableXxx() or List.of() / Map.of() (Java 9+):

// Unmodifiable wrapper (Java 1.2+)
List<String> mutable = new ArrayList<>(Arrays.asList("a","b","c"));
List<String> readonly = Collections.unmodifiableList(mutable);
readonly.add("d"); // UnsupportedOperationException

// Immutable factory (Java 9+)
List<String> immutable = List.of("a", "b", "c"); // cannot add/remove/set
Map<String, Integer> map = Map.of("one", 1, "two", 2);

Difference: unmodifiableList wraps the original — changes to the original are still visible. List.of() is truly immutable.


Q95. What is the difference between Iterator and ListIterator?

IteratorListIterator
Works withAny Collection (List, Set)List only
DirectionForward only (next())Forward and backward (previous())
Add elementsNoYes — add()
Replace elementsNoYes — set()
Get indexNoYes — nextIndex(), previousIndex()

Q96. What is PriorityQueue in Java?

PriorityQueue is a min-heap implementation — the smallest element is always at the head and dequeued first (natural ordering or Comparator).

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30); pq.add(10); pq.add(20);
System.out.println(pq.poll()); // 10 — smallest first

// Max-heap (reverse order)
PriorityQueue<Integer> maxPq = new PriorityQueue<>(Comparator.reverseOrder());
maxPq.add(30); maxPq.add(10); maxPq.add(20);
System.out.println(maxPq.poll()); // 30 — largest first

Use cases: Dijkstra's algorithm, task scheduling by priority, merge K sorted lists.


17. OOP — Advanced

Q97. What is aggregation vs composition?

Both are "has-a" relationships, but differ in lifecycle dependency:

Aggregation — weak relationship; child can exist independently of parent:

class Department {}
class University {
    List<Department> departments; // Department can exist without University
}

Composition — strong relationship; child's lifecycle is tied to parent:

class Room {}
class House {
    private Room room = new Room(); // Room created with House, destroyed with House
}

Summary: Composition implies ownership; aggregation implies usage.


Q98. What is the Strategy pattern?

Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.

interface SortStrategy {
    void sort(int[] arr);
}

class BubbleSort implements SortStrategy {
    public void sort(int[] arr) { /* bubble sort */ }
}
class QuickSort implements SortStrategy {
    public void sort(int[] arr) { /* quick sort */ }
}

class Sorter {
    private SortStrategy strategy;
    Sorter(SortStrategy s) { this.strategy = s; }
    void sort(int[] arr) { strategy.sort(arr); }
}

Sorter s = new Sorter(new QuickSort());
s.sort(data); // easily swap strategy without changing Sorter

Q99. What is the Decorator pattern?

Decorator adds behaviour to objects dynamically without subclassing — wraps the original object.

interface Coffee { double getCost(); String getDescription(); }
class SimpleCoffee implements Coffee {
    public double getCost() { return 1.0; }
    public String getDescription() { return "Coffee"; }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;
    MilkDecorator(Coffee c) { this.coffee = c; }
    public double getCost() { return coffee.getCost() + 0.25; }
    public String getDescription() { return coffee.getDescription() + ", Milk"; }
}

Coffee c = new MilkDecorator(new SimpleCoffee());
System.out.println(c.getDescription()); // "Coffee, Milk"
System.out.println(c.getCost());        // 1.25

Java's own BufferedReader wrapping FileReader is the classic decorator example.


Q100. What is the difference between static method and instance method?

Static methodInstance method
Belongs toClassObject (instance)
Access instance fields?NoYes
Call withClassName.method()object.method()
OverridingCannot be overridden (only hidden)Can be overridden in subclass
Use forUtility/helper methods (Math.sqrt, Collections.sort)Operations on object state

18. Java Keywords and Misc

Q101. What is the difference between break and continue?

  • break — exits the loop or switch immediately; control passes to the statement after the loop
  • continue — skips the rest of the current iteration and moves to the next iteration
for (int i = 0; i < 10; i++) {
    if (i == 5) break;    // exits loop at i=5 → prints 0,1,2,3,4
    System.out.println(i);
}

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue; // skip even → prints 1,3,5,7,9
    System.out.println(i);
}

Both can be used with a label to break/continue an outer loop:

outer:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (j == 1) break outer; // exits both loops
    }
}

Q102. What is instanceof vs isInstance()?

instanceofClass.isInstance()
TypeOperator (keyword)Method on Class object
Usageobj instanceof ClassNameclazz.isInstance(obj)
Dynamic class?No — class must be known at compile timeYes — can use any Class object at runtime
Use caseTypical runtime type checkReflection — checking against dynamically loaded classes
Object obj = "hello";
System.out.println(obj instanceof String); // true

Class<?> clazz = Class.forName("java.lang.String");
System.out.println(clazz.isInstance(obj)); // true — useful in reflection

Q103. What is the difference between import and static import?

  • import — imports a class or package so you can use the class name without the full qualified name
  • static import — imports static members (fields/methods) directly, so you can use them without the class name
import java.util.List;              // import class
import static java.lang.Math.PI;    // static import
import static java.lang.Math.sqrt;  // static import

double circumference = 2 * PI * r;  // no need for Math.PI
double root = sqrt(16);             // no need for Math.sqrt

Caution: Overusing static imports reduces readability by hiding where methods come from.


Q104. What is the difference between System.out.println() and System.err.println()?

  • System.out — standard output stream; used for normal program output
  • System.err — standard error stream; used for error messages and diagnostics

Both print to the console by default but they are separate streams. IDEs typically display System.err output in red. You can redirect them independently in shell:

java MyApp 1>output.txt 2>errors.txt

Q105. What is the ClassLoader in Java?

ClassLoaders load class files from the filesystem or network into the JVM at runtime.

ClassLoader hierarchy (parent-delegation model):

  1. Bootstrap ClassLoader — loads core JDK classes (java.lang, java.util) from rt.jar/modules
  2. Platform (Extension) ClassLoader — loads from $JAVA_HOME/lib/ext
  3. Application ClassLoader — loads from CLASSPATH (your application classes)

When loading a class, each loader delegates to its parent first. Only if the parent can't find it does the child try. This prevents user-defined java.lang.String from overriding the JDK's version.

ClassLoader cl = Thread.currentThread().getContextClassLoader();
System.out.println(cl); // sun.misc.Launcher$AppClassLoader
System.out.println(cl.getParent()); // sun.misc.Launcher$ExtClassLoader
System.out.println(cl.getParent().getParent()); // null (Bootstrap is native)

Q106. What is the Proxy class in Java?

java.lang.reflect.Proxy creates dynamic proxy classes at runtime that implement one or more interfaces, delegating all method calls to an InvocationHandler.

interface Greeter { void greet(String name); }

Greeter proxy = (Greeter) Proxy.newProxyInstance(
    Greeter.class.getClassLoader(),
    new Class[]{Greeter.class},
    (proxyObj, method, args) -> {
        System.out.println("Before: " + method.getName());
        // could delegate to real implementation here
        System.out.println("Hello, " + args[0]);
        return null;
    }
);

proxy.greet("Alice"); // "Before: greet" then "Hello, Alice"

Dynamic proxies power Spring AOP, JDK-based transaction management, and mock frameworks like Mockito.


Q107. What is the assert keyword in Java?

assert is used for debugging and testing invariants — conditions that should always be true at a given point. If the condition is false, an AssertionError is thrown.

int age = -1;
assert age >= 0 : "Age cannot be negative: " + age;

Assertions are disabled by default at runtime. Enable with JVM flag -ea (enable assertions):

java -ea MyApp

Use assertions for internal invariants, not for input validation from external callers (use IllegalArgumentException for that).


Q108. What is the difference between Error and Exception?

ErrorException
Caused byJVM/system-level problemsApplication-level problems
Should catch?No — indicates a fatal conditionYes — can be handled and recovered
ExamplesOutOfMemoryError, StackOverflowError, VirtualMachineErrorIOException, NullPointerException, IllegalArgumentException
RecoveryGenerally not recoverableOften recoverable with proper handling

Q109. What is tight coupling vs loose coupling?

Tight coupling — classes depend directly on concrete implementations:

class OrderService {
    private MySQLDatabase db = new MySQLDatabase(); // tightly coupled
}

Loose coupling — classes depend on interfaces/abstractions:

class OrderService {
    private Database db; // depends on interface
    OrderService(Database db) { this.db = db; } // injected from outside
}

Loose coupling is achieved via Dependency Injection, interfaces, and the Factory/Strategy patterns. It makes code easier to test, maintain, and swap implementations.


Q110. What is the difference between abstract class and concrete class?

  • Abstract class — cannot be instantiated; may have abstract methods that subclasses must implement. Defined with the abstract keyword.
  • Concrete class — a fully implemented class that can be instantiated with new.
abstract class Vehicle {
    abstract void startEngine(); // must be implemented
    void stop() { System.out.println("Stopped"); } // concrete
}

class Car extends Vehicle {
    void startEngine() { System.out.println("Car engine started"); }
}

Vehicle v = new Car(); // OK — Car is concrete
Vehicle x = new Vehicle(); // COMPILE ERROR — abstract class

Q111. What is autoboxing pitfall with null?

Unboxing a null wrapper causes NullPointerException:

Integer i = null;
int x = i; // NullPointerException — unboxing null

Always check for null before unboxing:

int x = (i != null) ? i : 0;

Also beware of performance: autoboxing in tight loops creates many short-lived objects:

Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
    sum += i; // autoboxes i → Long on every iteration!
}
// Use: long sum = 0L; instead

Q112. What is the purpose of the forEach() method in Iterable?

forEach(Consumer<T> action) was added in Java 8 to Iterable as a default method. It iterates over each element and passes it to the Consumer:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Traditional
for (String name : names) { System.out.println(name); }

// forEach with lambda
names.forEach(name -> System.out.println(name));

// forEach with method reference (most concise)
names.forEach(System.out::println);

Available on all Collections, and on Map via Map.forEach((k,v) -> ...).


Q113. What is String.valueOf() vs toString()?

String.valueOf(obj)obj.toString()
Null safeYes — returns "null" stringNo — throws NullPointerException if obj is null
UsageStatic method on String classInstance method on every Object
Prefer whenObject might be nullObject is guaranteed non-null

Q114. What are the primitive data types in Java?

Java has 8 primitive types:

TypeSizeRangeDefault
byte1 byte-128 to 1270
short2 bytes-32,768 to 32,7670
int4 bytes-2^31 to 2^31-10
long8 bytes-2^63 to 2^63-10L
float4 bytes~±3.4 x 10^38 (7 digits)0.0f
double8 bytes~±1.8 x 10^308 (15 digits)0.0d
char2 bytes0 to 65,535 (Unicode)''
booleanJVM dependenttrue or falsefalse

Q115. What is the switch statement? What changed in Java 14+?

Traditional switch:

int day = 3;
switch (day) {
    case 1: System.out.println("Mon"); break;
    case 2: System.out.println("Tue"); break;
    case 3: System.out.println("Wed"); break;
    default: System.out.println("Other");
}

Switch expression (Java 14+):

String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Other";
}; // no fall-through, no break needed

Switch with multiple labels and yield (Java 14+):

int result = switch (day) {
    case 1, 2, 3, 4, 5 -> 1; // weekday
    case 6, 7 -> { System.out.println("Weekend"); yield 0; }
    default -> -1;
};

Q116. What is the difference between Iterable and Iterator?

Iterable<T>Iterator<T>
PurposeMarks a class as iterable (can be used in for-each)The cursor that traverses the collection
Methoditerator() — returns an IteratorhasNext(), next(), remove()
StateStateless — creates a new Iterator each timeStateful — remembers current position
ReuseCan be iterated multiple timesSingle-use — exhausted after traversal

Q121. What is the difference between local, instance, and static variables?

Local variableInstance variableStatic (class) variable
Where declaredInside method/blockInside class, outside methodsInside class with static keyword
ScopeWithin the method/blockThroughout the objectThroughout the class (shared)
Default valueNone — must initialise before useType default (0, null, false)Type default (0, null, false)
MemoryStackHeap (with object)Method area (one copy per class)
LifetimeUntil method exitsUntil object is GC'dUntil class is unloaded

Q122. What is the difference between primitive types and reference types?

PrimitiveReference
StoresActual valueMemory address (reference to object)
MemoryStack (local) or inline in object (field)Reference on stack; object on heap
Default value0, 0.0, false, ''null
Examplesint, long, double, boolean, charString, arrays, objects, wrapper classes
Passed asCopy of valueCopy of reference (pass-by-value of the address)

Q123. Explain the final keyword for variables, methods, and classes.

final variable — value cannot be reassigned after initialisation:

final int MAX = 100;
MAX = 200; // compile error

final List<String> list = new ArrayList<>();
list.add("item"); // OK — reference is final, not the object
list = new ArrayList<>(); // compile error — cannot reassign reference

final method — cannot be overridden in a subclass:

class Animal {
    final void breathe() { System.out.println("Breathing"); }
}
class Dog extends Animal {
    void breathe() {} // compile error — cannot override final
}

final class — cannot be subclassed. String, Integer, Math are all final:

final class Immutable {}
class Sub extends Immutable {} // compile error

Q124. What is the difference between float and double?

floatdouble
Size32-bit (4 bytes)64-bit (8 bytes)
Precision~7 decimal digits~15-16 decimal digits
Default for decimal literalsNo — must suffix with f: 3.14fYes — 3.14 is a double by default
Use whenMemory constrained (large arrays, graphics)Default choice for decimal calculations

Never use float or double for currency — use BigDecimal instead:

System.out.println(0.1 + 0.2); // 0.30000000000000004 (floating point imprecision)
BigDecimal result = new BigDecimal("0.1").add(new BigDecimal("0.2")); // exact: 0.3

Q125. What is the difference between char and Character?

charCharacter
TypePrimitive (2 bytes, Unicode 0–65535)Wrapper object
Can be nullNoYes
CollectionsCannot use directly in List<char>Can use in List<Character>
Utility methodsNoneCharacter.isDigit(), isLetter(), toUpperCase()
char c = 'A';
Character ch = c; // autoboxing
System.out.println(Character.isUpperCase(c)); // true
System.out.println(Character.toLowerCase(c)); // 'a'

Q117. What is the enum type in Java?

enum defines a fixed set of named constants. Enums in Java are full classes:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

    public boolean isWeekend() {
        return this == SATURDAY || this == SUNDAY;
    }
}

Day d = Day.FRIDAY;
System.out.println(d.isWeekend()); // false
System.out.println(d.ordinal());   // 4 (0-based index)
System.out.println(d.name());      // "FRIDAY"

// Enum in switch
switch (d) {
    case SATURDAY, SUNDAY -> System.out.println("Weekend");
    default -> System.out.println("Weekday");
}

Enums are implicitly public static final and cannot be subclassed (except by other enums with abstract methods). They implement Serializable and Comparable by default.


Q118. What is the difference between abstract method and concrete method?

  • Abstract method — declared but not implemented; has no body; must be overridden in a non-abstract subclass
  • Concrete method — has a complete implementation (method body)
abstract class Shape {
    abstract double area();           // abstract — no body
    void describe() {                 // concrete — has body
        System.out.println("Shape with area: " + area());
    }
}

class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }
    double area() { return Math.PI * radius * radius; } // must implement
}

Q119. What is a nested class? What are the types?

A nested class is a class defined inside another class.

Typestatic?Access outer members?Use case
Static nested classYesOnly static membersBuilder pattern, utility grouping
Inner class (non-static)NoAll outer members (including private)Iterator implementations
Local classNoOuter members + effectively final localsComplex logic scoped to one method
Anonymous classNoOuter members + effectively final localsOne-off implementations; replaced by lambdas in Java 8+

Q120. What is the difference between SoftReference and WeakReference?

Both are collected by the GC but differ in urgency:

  • SoftReference — the GC collects it only when memory is low. Objects live as long as there's enough heap. Ideal for memory-sensitive caches.
SoftReference<byte[]> cache = new SoftReference<>(new byte[10_000_000]);
byte[] data = cache.get(); // may return null if collected
  • WeakReference — the GC collects it at the next GC cycle, regardless of memory pressure. Used for canonicalized mappings.
WeakReference<Object> ref = new WeakReference<>(new Object());
System.gc();
System.out.println(ref.get()); // likely null after GC

WeakHashMap uses weak references for keys — entries are automatically removed when the key is no longer strongly reachable.


Q126. What is encapsulation? Give a real example.

Encapsulation bundles data (fields) with the methods that operate on them, and restricts direct access to fields using access modifiers (private).

class BankAccount {
    private double balance; // hidden from outside

    public double getBalance() { return balance; } // controlled read

    public void deposit(double amount) {
        if (amount > 0) balance += amount; // validation enforced
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) { balance -= amount; return true; }
        return false;
    }
}

Benefits: data hiding, validation logic protected inside the class, internal representation can change without affecting callers (just keep the public API the same).


Q127. What is the difference between association, aggregation, and composition?

All three describe relationships between classes:

RelationshipTypeLifecycle dependencyExample
Association"uses-a"None — independent lifecyclesDoctor treats Patient
Aggregation"has-a" (weak)Child can exist without parentUniversity has Departments
Composition"has-a" (strong)Child destroyed with parentHouse has Rooms
// Aggregation — Department can exist without University
class University { List<Department> depts; }

// Composition — Room cannot exist without House
class House { private final Room room = new Room(); }

Q128. What is Dependency Injection (DI)?

Dependency Injection is a design pattern where a class receives its dependencies from the outside rather than creating them itself. It is the practical implementation of the Inversion of Control (IoC) principle.

Without DI (tightly coupled):

class OrderService {
    private PaymentService payment = new PayPalService(); // hard-wired dependency
}

With DI (loosely coupled):

class OrderService {
    private PaymentService payment;
    OrderService(PaymentService payment) { this.payment = payment; } // injected
}
// Caller decides which implementation to use
OrderService svc = new OrderService(new PayPalService());
OrderService svc2 = new OrderService(new StripeService()); // easy swap

Types of injection:

  • Constructor injection — dependency passed via constructor (recommended; makes dependencies explicit)
  • Setter injection — dependency passed via setter method (optional dependencies)
  • Field injection — dependency injected directly into field (Spring @Autowired; hard to test)

Spring Boot uses DI extensively through its IoC container.


Q129. What is the difference between List and Set?

ListSet
DuplicatesAllowedNot allowed
OrderInsertion order maintained (index-based)HashSet: no order; LinkedHashSet: insertion order; TreeSet: sorted
Access by indexYes — list.get(2)No
NullMultiple nulls allowedOne null (HashSet); none (TreeSet)
Use whenOrder matters or duplicates neededUnique elements, fast membership check

Q130. What is the difference between a process and a thread?

ProcessThread
DefinitionAn independent program in execution with its own memory spaceA unit of execution within a process; shares process memory
MemorySeparate — processes don't share memory by defaultShared — all threads in a process share heap and static fields
CommunicationIPC (sockets, pipes, shared memory)Direct via shared variables (requires synchronization)
Creation overheadHigh — full OS-level contextLow — shares parent process resources
Crash impactCrash only affects that processUnhandled exception in one thread can crash the entire process

Q131. What are the types of thread pools in Java?

Executors factory provides four main thread pool types:

// Fixed thread pool — fixed number of threads; tasks queue if all busy
ExecutorService fixed = Executors.newFixedThreadPool(10);

// Cached thread pool — creates threads on demand; reuses idle threads; unbounded
ExecutorService cached = Executors.newCachedThreadPool();

// Single thread executor — one thread; tasks executed sequentially
ExecutorService single = Executors.newSingleThreadExecutor();

// Scheduled thread pool — supports delay and periodic execution
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(4);
scheduled.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); // every second

Use newFixedThreadPool for controlled concurrency. Avoid newCachedThreadPool under heavy load — it can create thousands of threads.


Q132. What is OutOfMemoryError? What causes it?

OutOfMemoryError (OOM) is thrown by the JVM when it cannot allocate memory for an object even after running the GC.

Common causes:

  • Java heap space — too many large objects; memory leak (objects held longer than needed)
  • GC overhead limit exceeded — GC runs constantly but frees less than 2% of heap
  • Metaspace — too many dynamically generated classes (code generation frameworks)
  • Direct buffer memory — NIO direct buffers exceeding limit

How to fix:

  • Increase heap: -Xmx2g (max heap 2GB)
  • Find and fix memory leaks: use heap dumps (-XX:+HeapDumpOnOutOfMemoryError)
  • Use streaming/batching for large data instead of loading everything into memory

Q133. What is the difference between getPath(), getAbsolutePath(), and getCanonicalPath()?

File f = new File("../docs/file.txt");

f.getPath();          // "../docs/file.txt" — as given (may be relative)
f.getAbsolutePath();  // "C:/myapp/../docs/file.txt" — prepends CWD, keeps ..
f.getCanonicalPath(); // "C:/docs/file.txt" — resolves .., symlinks; throws IOException

Use getCanonicalPath() when you need the true resolved path — e.g., to prevent path traversal security vulnerabilities.


Q134. What is the difference between FileInputStream and BufferedInputStream?

  • FileInputStream — reads one byte at a time directly from disk (each read = one OS call)
  • BufferedInputStream — wraps a stream and reads large chunks into a buffer; OS calls are batched
// Slow — one OS call per byte
FileInputStream fis = new FileInputStream("file.dat");

// Fast — reads 8KB at a time into buffer; single bytes served from buffer
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file.dat"), 8192);

Always wrap FileInputStream with BufferedInputStream for text/sequential reading. Same applies to FileReaderBufferedReader.


Q135. What are channels and buffers in Java NIO?

Buffer — a fixed-size memory block that holds data for reading/writing. Key buffer classes: ByteBuffer, CharBuffer, IntBuffer.

Channel — a bidirectional conduit to a file or socket (like a stream but supports both read and write, and non-blocking).

// Write to file using channel + buffer
try (FileChannel fc = FileChannel.open(Paths.get("data.bin"),
        StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
    ByteBuffer buf = ByteBuffer.allocate(1024);
    buf.put("Hello NIO".getBytes());
    buf.flip(); // switch from write mode to read mode
    fc.write(buf);
}

// Read from file
try (FileChannel fc = FileChannel.open(Paths.get("data.bin"), StandardOpenOption.READ)) {
    ByteBuffer buf = ByteBuffer.allocate(1024);
    int bytesRead = fc.read(buf);
    buf.flip();
    byte[] data = new byte[bytesRead];
    buf.get(data);
    System.out.println(new String(data));
}

Key buffer states: position (where next read/write happens), limit (end of data), capacity (total size). flip() resets position to 0 and sets limit to current position.


Q136. What is RandomAccessFile?

RandomAccessFile supports both reading and writing to any position in a file — unlike streams which are sequential.

try (RandomAccessFile raf = new RandomAccessFile("data.bin", "rw")) {
    raf.seek(100);            // jump to byte 100
    raf.writeInt(42);         // write 4 bytes at position 100
    raf.seek(0);              // jump back to start
    int value = raf.readInt(); // read from start
}

Modes: "r" (read-only), "rw" (read-write), "rws" (sync writes to storage).

Used in: database engines, log file seekers, binary file editors.


Q137. What is the difference between File and Path (NIO)?

java.io.Filejava.nio.file.Path
IntroducedJava 1.0 (legacy)Java 7 (NIO.2)
Exception handlingReturns boolean on failure (silent errors)Throws IOException — explicit error handling
CapabilitiesBasic file operationsSymbolic links, file attributes, watch service, directory streams
Utility classNoneFiles class — copy, move, delete, readAllLines, walk
// Modern NIO approach
Path src = Paths.get("source.txt");
Path dst = Paths.get("dest.txt");
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.walk(Paths.get(".")).forEach(System.out::println); // recursive listing

Prefer Path + Files for all new code.


Q138. What is JSP (JavaServer Pages)?

JSP is a server-side technology that embeds Java code inside HTML to generate dynamic web content. JSP files are compiled into Servlets by the container on first request.

<%@ page language="java" contentType="text/html" %>
<html>
<body>
  <h1>Hello, <%= request.getParameter("name") %></h1>
  <%
    String user = (String) session.getAttribute("user");
    if (user != null) {
  %>
    <p>Welcome back, <%= user %></p>
  <% } %>
</body>
</html>

JSP lifecycle: Translation → Compilation → jspInit()_jspService() (per request) → jspDestroy()

JSP implicit objects: request, response, session, application, out, config, pageContext

Modern Java web development uses Spring MVC with Thymeleaf instead of JSP.


19. Advanced Miscellaneous

Q139. Can we override static methods in Java?

No — static methods belong to the class, not to instances. What looks like overriding a static method is actually method hiding.

class Parent {
    static void greet() { System.out.println("Parent"); }
}
class Child extends Parent {
    static void greet() { System.out.println("Child"); } // hides, not overrides
}

Parent obj = new Child();
obj.greet(); // prints "Parent" — resolved at compile time based on reference type
// With true overriding (instance method), it would print "Child"

The key difference: overriding uses dynamic dispatch (runtime); hiding uses static dispatch (compile time).


Q140. What is covariant return type?

Covariant return type allows an overriding method in a subclass to return a more specific (subtype) return type than the parent method.

class Animal {
    Animal create() { return new Animal(); }
}
class Dog extends Animal {
    Dog create() { return new Dog(); } // covariant — Dog is a subtype of Animal
}

Introduced in Java 5. Used extensively in the Builder pattern and clone() overrides.


Q141. What is var in Java 10+?

var enables local variable type inference — the compiler infers the type from the right-hand side. It is not dynamic typing; the type is still fixed at compile time.

var list = new ArrayList<String>(); // inferred as ArrayList<String>
var map = new HashMap<String, Integer>(); // inferred as HashMap<String, Integer>

for (var entry : map.entrySet()) { // entry inferred as Map.Entry<String, Integer>
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

Restrictions: var cannot be used for fields, method parameters, or return types — only local variables. Do not use when it reduces readability.


Q142. How do you check if a key exists in a HashMap vs null value?

map.get(key) returns null in two cases: key doesn't exist, or key maps to null. Use containsKey() to distinguish:

Map<String, String> map = new HashMap<>();
map.put("city", null); // key exists with null value
map.put("name", "Alice");

map.get("city");    // null — but key EXISTS
map.get("country"); // null — key DOES NOT EXIST

map.containsKey("city");    // true  — key exists
map.containsKey("country"); // false — key absent

// Safe retrieval with default
map.getOrDefault("country", "Unknown"); // "Unknown"

Q143. What is String.format()?

String.format() creates a formatted string using format specifiers — similar to printf in C:

String msg = String.format("Hello, %s! You have %d messages.", "Alice", 5);
// "Hello, Alice! You have 5 messages."

String pi = String.format("PI = %.2f", Math.PI); // "PI = 3.14"

String padded = String.format("%10s", "hi");  // "        hi" (right-aligned)
String left   = String.format("%-10s|", "hi"); // "hi        |" (left-aligned)

Common format specifiers: %s (String), %d (int/long), %f (float/double), %.2f (2 decimal places), %n (platform newline), %10d (width 10, right-aligned).


Q144. What is the ternary operator?

The ternary operator (? :) is a shorthand for a simple if-else that evaluates to a value:

// Syntax: condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;
String msg = (score >= 50) ? "Pass" : "Fail";

Equivalent to:

int max;
if (a > b) { max = a; } else { max = b; }

Nest sparingly — deeply nested ternaries hurt readability:

// Avoid — hard to read
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";

Q145. What is the difference between String concatenation with + vs StringBuilder?

Using + in a loop creates a new String object on every iteration — O(n²) time and memory:

String result = "";
for (int i = 0; i < 10000; i++) {
    result += i; // creates a new String every time — 10,000 objects!
}

StringBuilder appends to the same internal buffer — O(n) time:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
    sb.append(i); // modifies buffer in place
}
String result = sb.toString(); // single conversion at the end

Note: The Java compiler automatically replaces + concatenation of string literals (known at compile time) with StringBuilder internally. The problem only arises in loops with runtime values.


Q146. What is the purpose of hashCode() and equals()? What is the contract between them?

Every Java class inherits hashCode() and equals() from Object. The contract is:

  1. If a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true
  2. The reverse is not required — equal hash codes don't guarantee equal objects (hash collision)

Why this matters for HashMap: HashMap first compares hash codes to find the bucket, then uses equals() to find the exact key. If you override equals() without overriding hashCode(), two "equal" objects may go to different buckets and HashMap won't find them:

class Point {
    int x, y;
    // Only equals() overridden — hashCode() uses default (memory address)
    public boolean equals(Object o) {
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }
    // Missing: hashCode() override → HashMap breaks!
}

Map<Point, String> map = new HashMap<>();
map.put(new Point(1, 2), "origin");
map.get(new Point(1, 2)); // null — different hash! Bug.

Always override both together. IDEs and Lombok can generate them correctly.


Q147. What is the difference between Comparable.compareTo() return values?

compareTo(T other) must return:

  • negative integer — this object comes before other (this < other)
  • zero — objects are equal in ordering
  • positive integer — this object comes after other (this > other)
class Student implements Comparable<Student> {
    int marks;

    public int compareTo(Student other) {
        return this.marks - other.marks; // ascending by marks
        // return other.marks - this.marks; // descending
    }
}

Caution: this.marks - other.marks can overflow for large values. Safer:

return Integer.compare(this.marks, other.marks);

Q148. What is a functional interface? Can it have non-abstract methods?

A functional interface has exactly one abstract method (SAM — Single Abstract Method). It can have:

  • Any number of default methods (concrete)
  • Any number of static methods
  • Methods inherited from Object (like equals, toString) don't count
@FunctionalInterface
interface Validator<T> {
    boolean validate(T value); // the one abstract method

    default Validator<T> and(Validator<T> other) { // default — OK
        return value -> validate(value) && other.validate(value);
    }

    static <T> Validator<T> notNull() { return v -> v != null; } // static — OK
}

Validator<String> notEmpty = s -> !s.isEmpty();
Validator<String> notNull = Validator.notNull();
Validator<String> combined = notNull.and(notEmpty);

@FunctionalInterface is optional but recommended — it makes the compiler enforce the constraint.


Q149. What is the difference between checked exception handling with try-catch vs throws?

  • try-catch — handle the exception at the call site; execution continues normally after the catch block
  • throws — propagate the exception to the caller; the caller must handle it
// try-catch — handle here
public void readFile() {
    try {
        new FileReader("file.txt");
    } catch (FileNotFoundException e) {
        System.err.println("File not found: " + e.getMessage());
        // execution continues
    }
}

// throws — let caller handle
public void readFile() throws FileNotFoundException {
    new FileReader("file.txt"); // if not found, caller must deal with it
}

Rule of thumb: Catch exceptions where you have enough context to handle them meaningfully. Otherwise, declare throws and let a higher-level handler deal with it.


Q150. What is immutability? How do you make a class immutable?

An immutable class cannot have its state changed after construction. String, Integer, LocalDate are all immutable.

Rules to make a class immutable:

  1. Declare the class final (prevent subclassing)
  2. Make all fields private final
  3. No setter methods
  4. If fields are mutable objects, return defensive copies in getters
public final class Money {
    private final int amount;
    private final String currency;

    public Money(int amount, String currency) {
        this.amount = amount;
        this.currency = currency;
    }

    public int getAmount() { return amount; }
    public String getCurrency() { return currency; }

    // Return new object instead of modifying
    public Money add(Money other) {
        return new Money(this.amount + other.amount, this.currency);
    }
}

Benefits: thread-safe without synchronization, safe to use as HashMap keys, easier to reason about.


Q151. What is the difference between Strategy and Factory pattern?

Both are creational/behavioural patterns but serve different purposes:

Strategy PatternFactory Pattern
PurposeDefine interchangeable algorithms/behaviours and swap them at runtimeEncapsulate object creation logic — decide which class to instantiate
TypeBehavioural patternCreational pattern
FocusHOW to do something (algorithm choice)WHAT to create (object creation)
ExampleSorting algorithm selection at runtimeShapeFactory.create("circle")

Strategy in practice:

interface PaymentStrategy { void pay(int amount); }
class CreditCard implements PaymentStrategy { public void pay(int a) { System.out.println("Card: " + a); } }
class UPI implements PaymentStrategy { public void pay(int a) { System.out.println("UPI: " + a); } }

class Checkout {
    private PaymentStrategy strategy;
    Checkout(PaymentStrategy s) { this.strategy = s; }
    void complete(int amount) { strategy.pay(amount); }
}
new Checkout(new UPI()).complete(500); // swap strategy without changing Checkout

Q152. What is BufferedReader and when to use it?

BufferedReader wraps a Reader and provides buffered reading with the readLine() convenience method. Without a buffer, every read() call would result in an OS system call.

// Read a file line by line efficiently
try (BufferedReader br = new BufferedReader(
        new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

// Read from console
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String input = console.readLine();

Default buffer size is 8192 characters. Use new BufferedReader(reader, size) to customise.


Q153. What is the difference between ClassLoader and Class?

  • ClassLoader — a component responsible for loading class files (.class) into the JVM and creating Class objects from them
  • Class (java.lang.Class) — a runtime representation of a loaded class; provides metadata (methods, fields, constructors, annotations)
// Class object — metadata about a class
Class<?> clazz = String.class;
System.out.println(clazz.getName());           // java.lang.String
System.out.println(clazz.getDeclaredMethods().length); // all methods

// ClassLoader — who loaded this class?
ClassLoader cl = String.class.getClassLoader();
System.out.println(cl); // null — Bootstrap loaded String (native, not Java)

ClassLoader appCl = Main.class.getClassLoader();
System.out.println(appCl); // sun.misc.Launcher$AppClassLoader

Q154. What is the difference between String.equals() and String.equalsIgnoreCase()?

String a = "Hello";
String b = "hello";

a.equals(b);             // false — case-sensitive
a.equalsIgnoreCase(b);   // true  — ignores case

Both are null-safe when used as "literal".equals(variable) (avoids NPE if variable is null). Never use == to compare String content.


Q155. What is exception chaining?

Exception chaining (wrapping) preserves the original cause when re-throwing an exception, making the full stack trace available for debugging.

try {
    // low-level operation
    connection.open();
} catch (IOException e) {
    // wrap original cause in a higher-level exception
    throw new ServiceException("Failed to connect to database", e);
}

// ServiceException can be caught by the caller, who can get root cause:
try { service.init(); }
catch (ServiceException e) {
    System.out.println("Root cause: " + e.getCause().getMessage());
    e.printStackTrace(); // shows both exceptions in the chain
}

Q156. What is a try-catch-finally execution order?

try {
    System.out.println("try");
    if (true) throw new RuntimeException();
    System.out.println("never reached");
} catch (RuntimeException e) {
    System.out.println("catch");
} finally {
    System.out.println("finally"); // always runs
}
// Output: try → catch → finally

Edge cases:

  • If return is in try, finally still runs before the method actually returns
  • If System.exit() is called in try, finally does NOT run (JVM exits immediately)
  • If both catch and finally throw exceptions, the catch exception is suppressed and finally's exception propagates

Q157. What is the difference between Enumeration and Iterator?

EnumerationIterator
IntroducedJava 1.0 (legacy)Java 1.2 (Collections Framework)
MethodshasMoreElements(), nextElement()hasNext(), next(), remove()
Remove during iterationNoYes — via remove()
Used withLegacy — Vector, HashtableAll modern Collections

Use Iterator in all modern code. Enumeration only appears in legacy APIs.


Q158. What is the difference between TreeMap and HashMap?

HashMapTreeMap
Internal structureHash tableRed-Black Tree
Key orderingNo orderingSorted by natural order or Comparator
PerformanceO(1) average for get/putO(log n) for get/put
Null keysOne null key allowedNo null keys (comparison would throw NPE)
Extra methodsNonefirstKey(), lastKey(), headMap(), tailMap(), subMap()

Use TreeMap when you need entries sorted by key (e.g., leaderboard, range queries).


Q159. What is AtomicInteger and when to use it?

AtomicInteger provides thread-safe integer operations without synchronization, using CPU-level CAS (Compare-And-Swap) instructions.

AtomicInteger counter = new AtomicInteger(0);

// Thread-safe operations — no synchronized needed
counter.incrementAndGet();     // ++counter
counter.getAndIncrement();     // counter++
counter.addAndGet(5);          // counter += 5
counter.compareAndSet(5, 10);  // if current == 5, set to 10; returns true if swapped

// Example: thread-safe counter for concurrent requests
ExecutorService pool = Executors.newFixedThreadPool(10);
AtomicInteger requests = new AtomicInteger();
for (int i = 0; i < 1000; i++) {
    pool.submit(() -> requests.incrementAndGet());
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println(requests.get()); // always 1000

Use AtomicInteger for simple counters/flags shared across threads instead of synchronized. For complex logic involving multiple variables, still use synchronized.


Q160. What is the difference between sleep(), wait(), and yield()?

sleep(ms)wait()yield()
ClassThread (static)Object (instance)Thread (static)
Releases lock?NoYesNo
Resume conditionTime expires or interruptnotify() / notifyAll()Scheduler decides — may be immediate
Synchronized required?NoYesNo
PurposePause thread for fixed timeInter-thread communicationHint scheduler to run other threads

Struggling to Find a Job? These Startups Are Hiring ✅ Startup list

Spring Boot Interview Questions

JavaScript Interview Questions

SQL Interview Questions

Operating System Interview Questions

DBMS Interview Questions

System Design Roadmap

Join our WhatsApp Channel for daily job alerts and placement resources.