Updated March 2026

50+ Java Interview
Questions & Answers (2026)

Curated by Deen Bandhu — working Java developer & educator. These are questions actually asked at TCS, Infosys, Wipro, Capgemini, Cognizant, and product startups. Covers fresher to 1 years experience.

⏰ 45 min read 🎯 Freshers to 1 YOE ✅ 50+ Questions 🏫 Java 11–17

1. Core Java Basics

Q1.What is the difference between JDK, JRE, and JVM?
JVM executes bytecode and provides platform independence. JRE = JVM + runtime libraries needed to run Java apps. JDK = JRE + compiler (javac) + debugger + dev tools. To run Java you need JRE. To develop Java you need JDK.
Q2.Is Java pass-by-value or pass-by-reference?
Java is always pass-by-value. For primitives, the actual value is copied. For objects, the reference (memory address) is copied — not the object. You can mutate the object's state inside a method, but you cannot make the caller's variable point to a new object.
Q3.Difference between == and .equals()?
== compares references (same object in heap?). .equals() compares content. For String always use .equals(). Example: new String("abc") == new String("abc") is false; .equals() is true.
Q4.What is the String Pool?
A special area in the heap where String literals are cached. String s = "hello" checks the pool first — reuses existing "hello". new String("hello") always creates a new heap object bypassing the pool. Use .intern() to manually add to the pool.
Q5.What are final, finally, and finalize()?
final — keyword: constant variable, prevent overriding, prevent inheritance. finally — block always executed after try-catch (cleanup). finalize() — GC calls before destroying object (deprecated Java 9+, avoid it).
Q6.What is autoboxing and unboxing?
Autoboxing — automatic conversion from primitive to wrapper: intInteger. Unboxing — reverse. Happens automatically when you add an int to an ArrayList<Integer>. Beware: unboxing a null Integer throws NullPointerException.

2. OOP Concepts

Q7.What are the 4 pillars of OOP?
Encapsulation — bind data + methods; private fields + public getters/setters. Inheritance — subclass extends superclass with extends. Polymorphism — overloading (compile-time) and overriding (runtime). Abstraction — hide implementation via abstract class or interface.
Q8.Abstract class vs Interface — when to use which?
Abstract class: has state (fields), constructors, both abstract and concrete methods. A class can extend only one. Interface: pure contract. Multiple implementation allowed. Since Java 8: default and static methods allowed. Use interface for capability (Runnable, Comparable). Use abstract class for shared base (same family of objects).
Q9.What is method overloading vs overriding?
Overloading — same name, different parameters, same class. Compile-time polymorphism. Overriding — same name, same signature, in subclass. Runtime polymorphism. Always use @Override annotation — compiler will catch mistakes. You cannot override static, final, or private methods.
Q10.What is the difference between Composition and Inheritance?
Inheritance = "is-a" (Dog extends Animal). Composition = "has-a" (Car has an Engine). Prefer composition — more flexible, doesn't expose parent internals, easier to test. Inheritance creates tight coupling and can break when parent changes.
Q11.What is a Singleton pattern and how do you make it thread-safe?
Singleton ensures only one instance of a class exists. Thread-safe approach: use Bill Pugh / static inner class (no synchronization needed): private static class Holder { static final Singleton INSTANCE = new Singleton(); }. Alternatively use enum — simplest and safest Singleton in Java.

3. Collections Framework

Q12.ArrayList vs LinkedList — which to use when?
ArrayList: O(1) random access, O(n) insert/delete in middle. Backed by array. Better cache locality → faster in practice for most use cases. LinkedList: O(1) insert/delete at head/tail, O(n) access. Higher memory (node pointers). Use LinkedList only as a Queue/Deque.
Q13.HashMap vs LinkedHashMap vs TreeMap?
HashMap: no ordering, O(1) avg. LinkedHashMap: insertion-order preserved, slight overhead. TreeMap: sorted by key (natural or Comparator), O(log n). All allow null values; TreeMap doesn't allow null key. Choose based on ordering needs.
Q14.How does HashMap work internally?
Array of buckets (Node[]). On put(k,v): compute k.hashCode(), spread hash, bucket index = hash & (n-1). Collision → linked list in bucket (red-black tree from Java 8 when list > 8). Default capacity: 16, load factor: 0.75. Resizes (doubles) when 75% full. Always override both hashCode() and equals() for custom keys.
Q15.ConcurrentHashMap vs synchronized HashMap?
Collections.synchronizedMap() locks the entire map for every read/write — single lock = poor throughput under concurrency. ConcurrentHashMap uses per-bucket locking (Java 8: CAS + synchronized on individual buckets) — allows concurrent reads and multiple writes. Always prefer ConcurrentHashMap in multi-threaded code.
Q16.What is the difference between Iterator and ListIterator?
Iterator: forward-only traversal, available for all Collections. Methods: hasNext(), next(), remove(). ListIterator: bidirectional (forward + backward), only for Lists. Additional methods: hasPrevious(), previous(), add(), set(). Always use Iterator to safely remove during iteration (avoid ConcurrentModificationException).

4. Multithreading & Concurrency

Q17.Thread vs Runnable — which is better?
Prefer Runnable. Extending Thread wastes your one inheritance slot. Runnable separates task from thread mechanism. Best: use ExecutorService with Runnable or Callable (returns result via Future) — avoids creating raw threads and enables thread reuse.
Q18.What is synchronized?
Ensures only one thread executes a block/method at a time for a given object's monitor lock. On instance method: locks this. On static method: locks the Class object. On block: locks specified object. Prevents race conditions but hurts throughput under contention. Prefer ReentrantLock or concurrent collections where possible.
Q19.What is volatile?
Guarantees a variable is always read/written from main memory (not CPU cache). Provides visibility but NOT atomicity. Use for a simple boolean flag written by one thread, read by others. For compound actions (check-then-act), use AtomicBoolean / synchronized.
Q20.What is deadlock? How to prevent it?
Two threads each hold a lock the other needs — both wait forever. Prevention: 1) Lock ordering — always acquire locks in same global order. 2) tryLock with timeout via ReentrantLock. 3) Minimize lock scope. 4) Use higher-level concurrency (ConcurrentHashMap, BlockingQueue) instead of manual locks.
Q21.What is ExecutorService?
Manages a thread pool — reuses threads instead of creating new ones for every task. Types: newFixedThreadPool(n), newCachedThreadPool(), newSingleThreadExecutor(). Use submit(Callable) → returns Future. Always call shutdown() when done. Prefer over raw new Thread().

5. Exception Handling

Q22.Checked vs Unchecked exceptions?
Checked: compiler enforces handling. Must declare with throws or wrap in try-catch. Examples: IOException, SQLException. Unchecked: extend RuntimeException. Compiler doesn't enforce. Examples: NullPointerException, ArrayIndexOutOfBoundsException. Modern practice: prefer unchecked for programming errors, checked for recoverable situations.
Q23.What is try-with-resources?
Java 7+. Automatically closes any AutoCloseable resource (streams, connections, files) after the try block — even if exception is thrown. Cleaner than finally. Example: try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { ... }. Multiple resources closed in reverse declaration order.
Q24.Can you catch multiple exceptions in one catch block?
Yes, Java 7+ multi-catch: catch (IOException | SQLException e). The exception variable is implicitly final. Avoids code duplication when handling multiple exception types the same way. Can't catch exceptions that have an inheritance relationship in the same multi-catch block.

6. Java 8+ Features

Q25.What are Lambda Expressions?
Anonymous functions implementing a Functional Interface (single abstract method). Syntax: (params) -> body. Enable functional programming style. Example: list.sort((a, b) -> a.compareTo(b)) or method reference: list.forEach(System.out::println). Four built-in functional interfaces: Predicate, Function, Consumer, Supplier.
Q26.What is the Stream API?
Process collections declaratively in a pipeline. Intermediate (lazy, return Stream): filter(), map(), flatMap(), sorted(), distinct(), limit(). Terminal (eager, triggers execution): collect(), forEach(), count(), reduce(), findFirst(). Streams don't mutate source. Use parallelStream() for CPU-bound operations on large data.
Q27.What is Optional?
Container that may or may not hold a value — eliminates null returns. Optional.of(val), Optional.ofNullable(val), Optional.empty(). Key methods: isPresent(), orElse(default), orElseThrow(), map(fn), ifPresent(consumer). Never call get() without isPresent() — defeats the purpose.
Q28.What is a default method in interface?
Java 8 allows interfaces to have default methods with a body — lets you add new methods without breaking all implementing classes. Also allows static methods in interfaces. Diamond problem: if two interfaces have same default method, the implementing class must override it to resolve conflict.

7. JVM & Memory

Q29.What is Garbage Collection?
Automatically reclaims memory of unreachable objects. Heap = Young Gen (Eden + 2 Survivor spaces) + Old Gen. Minor GC cleans Young Gen (fast, frequent). Full GC cleans entire heap (slow, causes pauses). Collectors: G1GC (default Java 9+, predictable pauses), ZGC (sub-millisecond, Java 15+). System.gc() is just a hint — JVM may ignore it.
Q30.Stack vs Heap memory?
Stack: per-thread, stores method call frames + local variables + references. LIFO, auto-freed on method return. Fast, limited size (StackOverflowError). Heap: shared across all threads, stores all objects. GC-managed. All new allocations go here. Larger but slower. OutOfMemoryError when heap is full.

8. String & Immutability

Q31.Why is String immutable in Java?
String objects cannot be changed after creation. Benefits: Thread safety (safe to share across threads without synchronization), String Pool (safe to cache/reuse references), Security (class names, file paths can't be tampered after passing). The char[] inside String is private final.
Q32.String vs StringBuilder vs StringBuffer?
String: immutable — every concat creates a new object. StringBuilder: mutable, NOT thread-safe, fast — use for string building in single thread. StringBuffer: mutable, thread-safe (synchronized methods), slower — use when multiple threads modify same string. Modern Java: compiler converts String concatenation with + to StringBuilder automatically.
Java 2026Interview PrepOOP CollectionsMultithreadingJava 8 JVMFreshers0-3 YOE
AlgoVentra — Live Java Training

Get Interview-Ready with Live Mentorship

These questions are from Deen Bandhu's Java course — students learn to answer all of these, build real projects, and crack interviews at product companies.