■ Core Java 8
Interview Questions & Answers
Enhanced Edition — 150+ Questions
■ Tricky Questions Marked · Java Versions 8 → 26 Timeline · Placement-Ready
Section Topics Covered
1. JDK/JRE/JVM ClassLoader, JIT, GC, Metaspace (Java 8)
2. OOP Pillars, Polymorphism, Abstract vs Interface, Diamond Problem
3. Data Types Primitives, static, final, Autoboxing, Integer Cache
4. Collections HashMap internals, TreeMap, LinkedHashMap, ArrayDeque
5. Strings Immutability, Pool, StringBuilder, intern()
6. Exceptions Hierarchy, try-with-resources, finally traps
7. Streams & Lambdas Java 8 FP: Streams, Optional, CompletableFuture
8. Multithreading Thread lifecycle, synchronized, ThreadLocal, happens-before
9. Inner Classes Static nested, inner, anonymous, local — all 4 types
10. Generics Wildcards, PECS, type erasure, bounded types
11. Java 8 Date/Time LocalDate, Period, Duration, DateTimeFormatter
12. Tricky Questions Output traps, edge cases, interview gotchas
13. Java 9 → 26 Version-by-version feature timeline
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 1
1. Java Basics — JDK, JRE, JVM
Q1. What is the difference between JDK, JRE, and JVM?
Component Purpose Contains
JVM Executes bytecode ClassLoader, Execution Engine, GC, Memory areas
JRE Runtime environment JVM + core class libraries ([Link])
JDK Full development toolkit JRE + compiler (javac) + dev tools (jdb, jar, javadoc)
■ JDK ⊃ JRE ⊃ JVM. JDK is for developers; JRE is for end-users.
Q2. How does Java achieve platform independence?
Java source → javac → bytecode (.class) → JVM interprets/JIT compiles to native code. Bytecode is platform-independent;
JVM is platform-specific. 'Write Once, Run Anywhere.'
Q3. Explain JVM memory areas.
Area Stores Scope
Heap Objects, instance variables, arrays Shared across all threads
Stack Local variables, method frames, references Per thread
Method Area / Metaspace Class metadata, static vars, constant pool Shared (Metaspace since Java 8)
PC Register Address of current instruction Per thread
Native Stack Native method calls (JNI) Per thread
■ Java 8 IMPORTANT: PermGen was REMOVED. Replaced by Metaspace (native memory, auto-grows). No more
OutOfMemoryError: PermGen. Use -XX:MaxMetaspaceSize to cap it.
Q4. What is ClassLoader? Types?
ClassLoader loads .class files into JVM. Uses parent delegation model — child asks parent first before loading itself.
ClassLoader Loads
Bootstrap CL [Link], [Link] from [Link] (written in C++)
Extension CL jre/lib/ext directory
Application CL User classpath (-cp)
Custom CL User-defined loading logic (e.g., OSGi, app servers)
Q5. Is Java purely object-oriented? ■ TRICKY
No. Java has 8 primitive types (int, byte, short, long, float, double, char, boolean) that are NOT objects. Wrapper classes
(Integer, Character, etc.) provide object representation. Also static methods/fields can exist without object instances.
Q6. What happens internally when you run 'java MyClass'? ■ TRICKY
1. JVM starts → allocates Heap, Stack, Method Area/Metaspace
2. Bootstrap ClassLoader loads core classes
3. AppClassLoader loads [Link] → bytecode verified
4. Static variables initialized, static blocks executed (in order)
5. JVM looks for: public static void main(String[] args)
6. New thread 'main' created with its own Stack
7. main() frame pushed onto Stack → execution begins
Q7. What is JIT Compiler?
Just-In-Time compiler converts frequently executed bytecode (hotspots) into native machine code at runtime for performance.
JVM starts with interpreter; JIT kicks in for hot methods. JVM profiles which methods are hot (tiered compilation).
Q8. What is Garbage Collection? Explain generations and GC types.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 2
GC automatically reclaims memory from unreachable objects on the Heap. Cannot force GC — [Link]() is only a hint.
finalize() is deprecated.
Generation What lives here GC Type
Young Gen (Eden + S0/S1) New objects Minor GC — frequent, fast
Old Gen (Tenured) Long-lived objects (survived N minor GCs) Major GC — slower
Metaspace Class metadata Collected when class unloaded
GC Algorithms:
Algorithm Description When to use
Serial GC Single-threaded, stop-the-world Small apps, single CPU
Parallel GC Multi-threaded minor GC Throughput-focused (default Java 8)
G1 GC Region-based, predictable pause Large heaps (default Java 9+)
ZGC / Shenandoah Ultra-low pause (<1ms) Latency-critical apps
■ Memory leak trap: static collections holding references → objects never collected. Always remove from static collections when
done.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 3
2. OOP Concepts & Tricky Questions
Q9. What are the 4 pillars of OOP?
Pillar Definition Java Mechanism
Encapsulation Bundling data + methods, hiding internals private fields + public getters/setters
Inheritance Child acquires parent's properties extends / implements
Polymorphism Same interface, different behavior Overriding (runtime) + Overloading (compile-time)
Abstraction Hiding complexity, showing contract Abstract classes + Interfaces
Q10. Overloading vs Overriding?
Feature Overloading Overriding
Binding Compile-time Runtime
Where Same class Parent → Child
Parameters Must differ Must be same
Return type Can differ Same or covariant
Access Any Same or wider
static Can overload Cannot override (hidden)
private Can overload Cannot override (not inherited)
Q11. Abstract Class vs Interface (Java 8)?
Feature Abstract Class Interface (Java 8+)
Constructors Yes No
Fields Any access modifier Only public static final
Methods Abstract + concrete Abstract + default + static
Multiple inheritance Single only Multiple allowed
State Can have instance state No instance state
Use when Shared state + partial impl Pure contract / capability
Q12. Can we override static methods? ■ TRICKY
No. Static methods are resolved at compile time based on reference type. If child defines same static method, it is METHOD
HIDING, not overriding.
Parent p = new Child();
[Link](); // calls [Link]() — resolved by reference type, not object
Q13. Can a constructor be final, static, or abstract? ■ TRICKY
No to all three. final — constructors are not inherited, so final is meaningless. static — constructors initialize instance state,
contradicts static. abstract — constructors must have a body.
Q14. What is the Diamond Problem? How does Java 8 solve it?
If two interfaces have the same default method, the implementing class MUST override it or it is a compile error.
interface A { default void hello() { [Link]("A"); } }
interface B { default void hello() { [Link]("B"); } }
class C implements A, B {
@Override public void hello() { [Link](); } // explicitly choose
}
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 4
Q15. What is the output? (Polymorphism trap) ■ TRICKY
class A { int x = 10; void show() { [Link]("A"); } }
class B extends A { int x = 20; void show() { [Link]("B"); } }
A obj = new B();
[Link](obj.x); // 10 — variables: compile-time (reference type)
[Link](); // B — methods: runtime (actual object type)
■ Rule: Variables → compile-time binding (reference type). Methods → runtime binding (object type).
Q16. What happens if parent has no no-arg constructor and child doesn't call super()? ■ TRICKY
Compiler auto-inserts super() (no-arg call). If parent has ONLY a parameterized constructor, compile error.
class Parent { Parent(int x) { } }
class Child extends Parent {
Child() { } // ERROR: no default constructor in Parent
// Fix: Child() { super(10); }
}
Q17. What is the equals() and hashCode() contract?
If [Link](b) == true, then [Link]() == [Link]() MUST be true. Violation breaks HashMap/HashSet — equal
objects land in different buckets. Always override BOTH together.
Q18. Can an abstract class have a constructor? ■ TRICKY
Yes. It is called via super() when a concrete subclass is instantiated. Used to initialize common/shared fields.
Q19. What is Covariant Return Type?
Overridden method can return a subtype of the parent's return type.
class Animal { Animal create() { return new Animal(); } }
class Dog extends Animal {
@Override Dog create() { return new Dog(); } // Dog is subtype of Animal
}
Q20. Association vs Aggregation vs Composition?
Type Relationship Lifecycle Example
Association Uses-a (loose) Independent Teacher ↔ Student
Aggregation Has-a (weak) Child survives parent Department → Employee
Composition Has-a (strong) Child dies with parent House → Room
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 5
3. Data Types, Variables & Tricky Questions
Q21. Primitive Data Types
Type Size Default Range
byte 1B 0 -128 to 127
short 2B 0 -32,768 to 32,767
int 4B 0 -2^31 to 2^31-1
long 8B 0L -2^63 to 2^63-1
float 4B 0.0f ~±3.4E38 (7 sig digits)
double 8B 0.0d ~±1.7E308 (15 sig digits)
char 2B '\u0000' 0 to 65,535 (Unicode)
boolean ~1 bit false true / false
■ Defaults apply ONLY to instance/static fields. Local variables must be explicitly initialized before use.
Q22. static keyword in detail
Usage Behavior
static variable One shared copy for all instances (class-level)
static method Called via class name; no 'this' access; cannot access instance members
static block Runs once when class is loaded (before main)
static inner class No reference to outer instance needed
■ Static methods cannot be overridden — only hidden. They are resolved at compile time.
Q23. final keyword in detail
final int MAX = 100; // constant — cannot reassign
final List list = new ArrayList<>();
[Link]("hello"); // OK — object mutation allowed
// list = new ArrayList<>(); // ERROR — reference reassignment blocked
■ final variable = constant reference. final method = cannot override. final class = cannot extend (e.g., String). final ≠ immutable.
Q24. Output? (Integer Cache trap) ■ TRICKY
Integer a = 127, b = 127;
[Link](a == b); // true — cached range: -128 to 127
Integer c = 128, d = 128;
[Link](c == d); // false — outside cache, new objects created
■ Always use .equals() for wrapper comparison, NEVER ==.
Q25. Output? (Type promotion in compound assignment) ■ TRICKY
byte b = 10;
b = b + 1; // ERROR: b+1 promotes to int, cannot assign to byte
b += 1; // OK: += has implicit cast: (byte)(b+1)
Q26. Output? (String + int evaluation) ■ TRICKY
[Link](10 + 20 + "Hello"); // "30Hello" — 10+20=30 first, then concat
[Link]("Hello" + 10 + 20); // "Hello1020" — concat left to right
Q27. Output? (Char arithmetic) ■ TRICKY
char c = 'A';
[Link](c + 1); // 66 — char promoted to int
[Link]((char)(c+1)); // B — cast back to char
[Link]("" + c + 1); // A1 — string concat
Q28. Explain pass-by-value in Java
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 6
Java is ALWAYS pass-by-value. For objects, the reference (memory address) is copied, not the object itself.
void modify(StringBuilder sb) {
[Link](" World"); // OK — modifies original object via copied reference
sb = new StringBuilder("New"); // Only reassigns LOCAL copy of reference
}
StringBuilder s = new StringBuilder("Hello");
modify(s);
[Link](s); // "Hello World"
Q29. Access Modifiers
Modifier Same Class Same Package Subclass Everywhere
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
Q30. transient vs volatile
transient — excludes field from serialization (e.g., password, cached values). volatile — field always read/written from main
memory (guarantees visibility across threads). volatile does NOT guarantee atomicity.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 7
4. Collections & HashMap Internals
Q31. Collection Hierarchy
Iterable → Collection
■■■ List: ArrayList, LinkedList, Vector → Stack
■■■ Set: HashSet, LinkedHashSet, TreeSet
■■■ Queue: PriorityQueue, ArrayDeque, LinkedList
Map (NOT part of Collection): HashMap, LinkedHashMap, TreeMap,
Hashtable, ConcurrentHashMap
Q32. ArrayList vs LinkedList
Operation ArrayList LinkedList
get(index) O(1) — direct array access O(n) — traverse nodes
add(end) O(1) amortized (resize at capacity) O(1) — add tail node
add/remove(middle) O(n) — shift elements O(1) if already at node
Memory Less (contiguous array) More (node + 2 pointers)
Iteration Cache-friendly Cache-unfriendly (scattered)
■ Use ArrayList in 99% of cases. LinkedList only when you have frequent insertions/deletions at known positions.
Q33. How does HashMap work internally? (put & get)
Structure: Array of Node buckets. Each bucket is a linked list, or a Red-Black Tree if too many collisions.
// put(key, value):
1. hash = [Link]() ^ (hashCode >>> 16) // spread bits evenly
2. index = hash & (capacity - 1) // find bucket
3. Bucket empty → insert new Node
4. Key exists (via equals()) → replace value
5. Collision → add to linked list at bucket
6. List size >= 8 AND capacity >= 64 → convert to Red-Black Tree (Java 8)
7. Total entries > capacity * 0.75 → RESIZE (double, rehash all)
// get(key): same hash → find bucket → equals() match
// Linked list: O(n) | Red-Black Tree: O(log n)
Property Value
Default capacity 16
Load factor 0.75
Treeify threshold 8 (and capacity >= 64)
Untreeify threshold 6
Null key 1 allowed (stored at index 0)
Q34. What happens if two keys have the same hashCode? ■ TRICKY
Hash collision. Both go to same bucket as linked list/tree. During get(), equals() is used to find the exact match. Performance
degrades from O(1) to O(n) for linked list, O(log n) for tree.
Q35. What happens if a mutable key is modified after put()? ■ TRICKY
hashCode changes → entry is in old bucket → get() searches new bucket → entry is LOST (unreachable). Always use
immutable objects (String, Integer, enums) as HashMap keys.
Q36. Why is HashMap capacity always a power of 2? ■ TRICKY
index = hash & (capacity-1) — bitwise AND is faster than modulo %. Works correctly ONLY when capacity = 2^n. HashMap
rounds up: new HashMap(10) → actual capacity 16.
Q37. HashMap vs ConcurrentHashMap vs Hashtable
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 8
Feature HashMap ConcurrentHashMap Hashtable
Thread-safe No Yes Yes
Null key 1 allowed Not allowed Not allowed
Null value Allowed Not allowed Not allowed
Locking None Segment/bucket-level CAS Entire map (legacy)
Performance Fastest Good concurrent Slow
Q38. Fail-fast vs Fail-safe Iterator
Fail-fast: Throws ConcurrentModificationException if collection is modified during iteration (ArrayList, HashMap — uses
modCount). Fail-safe: Works on a copy, no exception (ConcurrentHashMap, CopyOnWriteArrayList).
// Safe removal from List:
[Link](s -> [Link]("x")); // Java 8
[Link](); // via Iterator
Q39. How does HashSet work internally?
Backed by HashMap. Element stored as KEY, dummy PRESENT object as value. Uniqueness via hashCode() + equals().
Q40. TreeMap vs HashMap vs LinkedHashMap
Feature HashMap LinkedHashMap TreeMap
Order None (random) Insertion order (or access order) Sorted by key
Performance O(1) avg O(1) avg O(log n)
Null key 1 allowed 1 allowed Not allowed
Backed by Hash table Hash table + doubly linked list Red-Black Tree
Use for General purpose LRU Cache, preserve order Sorted/range queries
■ LRU Cache = LinkedHashMap(capacity, 0.75f, true) — accessOrder=true. Override removeEldestEntry() to auto-evict.
Q41. ArrayDeque vs Stack
Stack extends Vector (legacy, synchronized = slow). ArrayDeque is faster for both stack (LIFO) and queue (FIFO) use.
Deque stack = new ArrayDeque<>();
[Link](1); // addFirst
[Link](); // removeFirst
[Link](); // peekFirst — no removal
// NEVER use [Link] in new code
Q42. Comparable vs Comparator
Feature Comparable Comparator
Method compareTo(T other) compare(T o1, T o2)
Modifies class? Yes (implements Comparable) No (external class/lambda)
Sort orders One natural order Multiple custom orders
Package [Link] [Link]
[Link]([Link](Emp::getName)
.thenComparing(Emp::getAge)
.reversed());
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 9
5. Strings in Java
Q43. String vs StringBuilder vs StringBuffer
Feature String StringBuilder StringBuffer
Mutable? No Yes Yes
Thread-safe? Yes (immutable) No Yes (synchronized)
Speed Slow for concat Fastest Slower than Builder
Use when Fixed/read-only text Single-threaded concat Multi-threaded concat
Q44. Why is String immutable?
Five reasons: (1) String Pool sharing — safe because value never changes. (2) Thread safety — safe to share across
threads. (3) Security — used in class loading, JDBC URLs, network connections. (4) hashCode caching — computed once
and cached. (5) Class loading safety.
Q45. How does String Pool work?
String s1 = "hello"; // String Pool (Heap)
String s2 = "hello"; // same pool reference
String s3 = new String("hello"); // new heap object (outside pool)
s1 == s2 // true (same pool ref)
s1 == s3 // false (different objects)
[Link](s3) // true (same content)
[Link]() == s1 // true (intern() returns pool ref)
■ String Pool is in Heap since Java 7 (was in PermGen before). intern() moves string to pool.
Q46. How many objects does new String('hello') create? ■ TRICKY
Up to 2. (1) 'hello' literal in String Pool (if not already there). (2) new String() object on heap. If 'hello' already in pool, only 1
new object is created.
Q47. Output? (Compile-time vs runtime concat) ■ TRICKY
String s1 = "Hello";
String s2 = "Hel" + "lo"; // compile-time constant → pool → same as s1
String s3 = "Hel";
String s4 = s3 + "lo"; // runtime → new heap object
s1 == s2 // true — both resolve to pool at compile time
s1 == s4 // false — runtime creates new object
Q48. Output? (final + String concat) ■ TRICKY
final String s1 = "Hel";
String s2 = s1 + "lo";
[Link](s2 == "Hello"); // true
// final makes s1 a compile-time constant, so s1+"lo" = "Hello" at compile time
Q49. Why is String a final class?
To guarantee immutability. If extendable, a subclass could add mutable behavior, breaking String Pool sharing, hashCode
caching, and security contracts (class loading, network).
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 10
6. Exception Handling & Tricky Questions
Q50. Exception Hierarchy
Throwable
■■■ Error (unrecoverable: OutOfMemoryError, StackOverflowError)
■■■ Exception
■■■ RuntimeException (unchecked: NPE, ClassCast, IllegalArgument)
■■■ Checked (IOException, SQLException, ClassNotFoundException)
Q51. Checked vs Unchecked Exceptions
Feature Checked Unchecked
Verified Compile time Runtime
Must handle? Yes (try-catch or throws) No
Extends Exception RuntimeException
Cause External (file, DB, network) Programming bugs (null, bounds)
Examples IOException, SQLException NullPointerException, ArrayIndexOutOfBounds
Q52. throw vs throws
void process() throws IOException { // declaration — method MAY throw
throw new IOException("error"); // action — actually throws it
}
Q53. Output? (finally + return) ■ TRICKY
static int test() {
try { return 1; }
catch (Exception e) { return 2; }
finally { return 3; } // OVERRIDES try/catch return
}
test(); // returns 3
■ NEVER put return in finally — it silently swallows exceptions.
Q54. Can finally NOT execute? ■ TRICKY
Yes: [Link]() called before finally, JVM crash, daemon thread killed by JVM shutdown, infinite loop/deadlock in try block.
Q55. Catch order: Exception before IOException? ■ TRICKY
Compile error — IOException becomes unreachable. Must order: most specific (IOException) → most general (Exception).
Q56. Can overriding method throw different exceptions? ■ TRICKY
class Parent { void read() throws IOException { } }
class Child extends Parent {
void read() throws FileNotFoundException { } // OK — subclass of IOException
// void read() throws Exception { } // ERROR — broader
// void read() throws SQLException { } // ERROR — unrelated checked
}
■ Rule: Overriding method can throw same, subclass, no exception, or any UNCHECKED. Cannot throw broader or unrelated
checked exceptions.
Q57. Output? (finally value trap) ■ TRICKY
static String test() {
String s = "initial";
try { s = "try"; return s; }
finally { s = "finally"; } // modifies local var, but return value already saved
}
test(); // returns "try"
Q58. try-with-resources
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 11
Resources implementing AutoCloseable are auto-closed in REVERSE order of declaration (LIFO). close() is called even if
exception occurs.
try (A a = new A(); B b = new B()) {
[Link]("Body");
}
// Output: A opened → B opened → Body → B closed → A closed
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 12
7. Streams, Lambda & Functional Interfaces (Java 8)
Q59. What is a Lambda Expression?
Concise anonymous function implementing a functional interface. Enables functional programming style in Java.
Runnable r = () -> [Link]("Hello");
Comparator c = (a, b) -> [Link](b);
// Method reference (shorthand for lambda):
Comparator c2 = String::compareTo;
Q60. What is a Functional Interface? Key built-in ones?
Interface with exactly ONE abstract method. Annotated @FunctionalInterface (optional but recommended).
Interface Signature Use
Predicate<T> T → boolean Filtering
Function<T,R> T→R Transformation
Consumer<T> T → void Side effects (print, save)
Supplier<T> () → T Factory / lazy value
UnaryOperator<T> T→T Same-type transform
BinaryOperator<T> (T,T) → T Combine two same-type values
BiFunction<T,U,R> (T,U) → R Two inputs, one output
Q61. Method Reference Types
Type Syntax Example
Static Class::staticMethod Integer::parseInt
Instance (bound) obj::method [Link]::println
Instance (unbound) Class::instanceMethod String::toUpperCase
Constructor Class::new ArrayList::new
Q62. Stream vs Collection
Feature Collection Stream
Storage Stores elements in memory No storage — computes on demand
Consumption Multiple iterations Consumed ONCE — reuse throws exception
Evaluation Eager Lazy (until terminal operation)
Modifies source? Yes (mutable) Never modifies source
Q63. Intermediate vs Terminal Operations
Intermediate (lazy, return Stream): filter, map, flatMap, sorted, distinct, peek, limit, skip
Terminal (trigger execution, return result): collect, forEach, reduce, count, min, max, findFirst, anyMatch, allMatch,
noneMatch, toArray
Q64. Common Stream Operations
// Filter + Map + Collect
[Link]().filter(e -> [Link]() > 50000)
.map(Employee::getName).collect([Link]());
// GroupBy + Counting
[Link]().collect([Link](Employee::getDept, [Link]()));
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 13
// Partition into two groups
[Link]().collect([Link](e -> [Link]() > 50000));
// Join strings
[Link]().map(Employee::getName).collect([Link](", "));
// FlatMap — flatten nested lists
[Link]().flatMap(Collection::stream).collect([Link]());
// Sort descending
[Link]().sorted([Link](Employee::getSalary).reversed());
// Infinite stream
[Link](0, n -> n + 2).limit(10).forEach([Link]::println); // 0,2,4...
[Link](Math::random).limit(5).collect([Link]());
Q65. map() vs flatMap()? ■ TRICKY
map() — 1-to-1 (each element → one element, may nest). flatMap() — 1-to-many then FLATTEN (each element → stream →
merged into one stream).
List words = [Link]("Hello World", "Java 8");
[Link]().map(w -> [Link](" "));
// Returns Stream — nested, NOT flat
[Link]().flatMap(w -> [Link]([Link](" ")));
// Returns Stream — flat: [Hello, World, Java, 8]
Q66. Can we reuse a Stream? ■ TRICKY
Stream s = [Link]();
[Link]([Link]::println); // OK
[Link]([Link]::println); // IllegalStateException: stream already closed
Q67. What is Optional?
Container that may or may not hold a non-null value. Avoids NullPointerException. Use only as method return type — NOT for
fields, parameters, or collections.
Optional opt = [Link](getName());
[Link]("default"); // always evaluates default
[Link](() -> computeDefault()); // lazy — only if empty
[Link](() -> new RuntimeException()); // throw if empty
[Link](String::toUpperCase).orElse(""); // transform if present
[Link]([Link]::println); // consume if present
[Link](s -> [Link]() > 3); // filter
Q68. orElse() vs orElseGet()? ■ TRICKY
orElse(value) — value expression is ALWAYS evaluated even if Optional is not empty (eager). orElseGet(supplier) —
supplier called ONLY if Optional is empty (lazy). Use orElseGet() when default is expensive to compute.
Q69. What is 'effectively final' for lambdas? ■ TRICKY
int x = 10;
Runnable r = () -> [Link](x); // OK — effectively final
int y = 10; y = 20;
Runnable r2 = () -> [Link](y); // ERROR — y is reassigned
■ Why: lambdas capture a COPY of the variable. If it changed, the copy would be stale. Hence must be final or effectively final.
Q70. Parallel Streams — when to use and when NOT to?
[Link]().filter(...).collect(...)
// Uses [Link]() — default threads = CPU cores
Use parallel when Avoid parallel when
Large dataset (thousands+) Small collections
CPU-intensive operations I/O-bound operations
Order doesn't matter Order matters (use forEachOrdered)
Operations are stateless Shared mutable state (race conditions)
■ Parallel is NOT always faster. Thread coordination overhead can make it slower than sequential for small lists.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 14
8. Multithreading
Q71. Ways to create a Thread
// 1. Extend Thread (limited — single inheritance)
class MyThread extends Thread { public void run() { ... } }
// 2. Implement Runnable (preferred — no return, no checked exception)
new Thread(() -> [Link]("task")).start();
// 3. Callable + Future (returns result, can throw checked exception)
Callable c = () -> 42;
Future f = [Link]().submit(c);
[Link](); // blocks until result ready
Q72. Thread Lifecycle
NEW →(start())→ RUNNABLE →(CPU assigned)→ RUNNING
↑ ↓
BLOCKED / WAITING / TIMED_WAITING
RUNNING →(run() completes)→ TERMINATED
Q73. What happens if you call run() instead of start()? ■ TRICKY
Thread t = new Thread(() -> [Link]([Link]().getName()));
[Link](); // prints "main" — no new thread, just a method call
[Link](); // prints "Thread-0" — new thread created and scheduled
Q74. synchronized keyword — what lock does each form use?
public synchronized void method() { } // locks 'this' object
public static synchronized void sMethod() { } // locks [Link] object
synchronized(lockObj) { } // locks specific 'lockObj'
// GOTCHA: static + instance synchronized do NOT block each other
// (different locks: class object vs instance object)
Q75. sleep() vs wait()
Feature sleep() wait()
Class Thread (static method) Object
Releases lock? NO — holds lock while sleeping YES — releases lock
Where Anywhere Inside synchronized block only
Wakes by Time expiry notify() / notifyAll()
Q76. What is Deadlock?
Two or more threads each hold a lock the other needs → infinite wait. Four conditions: mutual exclusion, hold and wait, no
preemption, circular wait. Prevention: always acquire locks in the same order, use tryLock() with timeout.
Q77. What is ThreadLocal?
ThreadLocal tl = [Link](() -> 0);
[Link](10); // sets value for CURRENT thread only
[Link](); // gets CURRENT thread's value
[Link](); // MUST call to avoid memory leak in thread pools
// Real use: Spring SecurityContextHolder, request-scoped data
// Each thread has its own isolated copy — no synchronization needed
■ Memory leak trap: Thread pool threads are reused. If you don't call [Link](), previous thread's data leaks to next task.
Q78. happens-before relationship
Guarantee that one action's result is visible to another action. Key rules:
happens-before rule Meaning
Monitor unlock → re-lock Changes before unlock visible after re-lock
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 15
volatile write → volatile read Volatile write visible to subsequent reads
[Link]() → thread code All actions before start() visible in new thread
Thread join → caller All thread actions visible after join()
Q79. Is volatile enough for count++? ■ TRICKY
// volatile guarantees VISIBILITY only — not atomicity
// count++ is 3 operations: read → increment → write (not atomic)
volatile int count = 0;
count++; // RACE CONDITION — two threads can read same value
// Fix 1: AtomicInteger (lock-free CAS)
AtomicInteger count = new AtomicInteger(0);
[Link]();
// Fix 2: synchronized
synchronized(this) { count++; }
Q80. ExecutorService Types
[Link](4); // fixed N threads
[Link](); // grows/shrinks with demand
[Link](); // 1 worker (sequential)
[Link](2); // delayed / periodic tasks
Q81. CompletableFuture (Java 8)
[Link](() -> fetchData()) // async supplier
.thenApply(data -> process(data)) // transform result
.thenAccept(result -> save(result)) // consume result
.exceptionally(ex -> { log(ex); return null; }); // handle error
[Link](f1, f2, f3).join(); // wait for ALL
[Link](f1, f2, f3); // first to complete
Q82. Key Concurrent Utilities
Class Purpose
AtomicInteger / AtomicLong Lock-free atomic operations using CAS
ReentrantLock Explicit lock with tryLock(), fairness option
CountDownLatch Wait for N tasks to complete (one-time use)
CyclicBarrier N threads wait for each other at a barrier (reusable)
Semaphore Limit number of concurrent accesses
ConcurrentHashMap Thread-safe Map without full synchronization
CopyOnWriteArrayList Thread-safe List — creates copy on write (read-heavy)
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 16
9. Inner Classes
Q83. 4 Types of Inner Classes
Type static? Accesses outer? Use case
Static Nested Yes Only static members Helper/utility class
Inner Class No All outer members (instance) Iterator pattern, builder
Anonymous Class No Effectively final vars One-time interface impl
Local Class No Effectively final vars Rare, method-scoped
Q84. Why can't a non-static inner class have static members? ■ TRICKY
Non-static inner class is tied to an outer instance. Static members imply no instance dependency. This is a contradiction.
(Exception: static final constants are allowed.)
Q85. Static Nested vs Inner Class
class Outer {
static class Nested { // static nested — no outer instance needed
void method() { } // cannot access Outer's instance fields
}
class Inner { // inner class — needs outer instance
void method() {
[Link]([Link]); // accesses outer instance
}
}
}
[Link] n = new [Link](); // no Outer instance needed
[Link] i = new Outer().new Inner(); // Outer instance required
Q86. Anonymous Class example
Runnable r = new Runnable() {
@Override public void run() { [Link]("anonymous"); }
};
// Java 8 equivalent (cleaner):
Runnable r2 = () -> [Link]("lambda");
■ Anonymous classes were the pre-Java-8 way to implement functional interfaces. Now use lambdas instead.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 17
10. Generics & Type Erasure
Q87. What are Generics? Why use them?
Generics provide compile-time type safety. Catch ClassCastException at compile time instead of runtime. No casting needed
when retrieving from collections.
// Without generics (pre-Java 5):
List list = new ArrayList();
[Link]("hello");
String s = (String) [Link](0); // cast needed, runtime risk
// With generics:
List list = new ArrayList<>();
[Link]("hello");
String s = [Link](0); // no cast, compile-time safe
Q88. What is Type Erasure? ■ TRICKY
Generics are a compile-time feature. At runtime, all generic type info is REMOVED (erased). List and List are both just List at
runtime. This is why you cannot do: new T(), [Link], or instanceof List.
// At compile time: List
// At runtime (erased): List (raw type)
// Cannot do:
// T obj = new T(); // ERROR — T unknown at runtime
// if (list instanceof List) // ERROR — erased
Q89. Wildcards — ? extends T vs ? super T (PECS)
PECS: Producer Extends, Consumer Super.
// ? extends T = upper bound = Producer (read from it)
List nums; // can read as Number, cannot add
Number n = [Link](0); // OK
// [Link](1.5); // ERROR — unknown exact subtype
// ? super T = lower bound = Consumer (write to it)
List ints; // can add Integer, read only as Object
[Link](42); // OK
// Integer i = [Link](0); // ERROR — unknown exact supertype
// Mnemonic: PECS — Producer Extends, Consumer Super
// If you only READ from list → extends. If you only WRITE → super.
Q90. Generic Method vs Generic Class
// Generic class
class Box { private T value; ... }
// Generic method (type param before return type)
public T getFirst(List list) { return [Link](0); }
// Bounded type parameter
public > T max(T a, T b) {
return [Link](b) >= 0 ? a : b;
}
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 18
11. Java 8 Date/Time API
Q91. Why was old Date/Calendar replaced?
Problem with old API Solution in Java 8
[Link] is mutable — not thread-safe LocalDate, LocalTime, Instant are immutable
Month was 0-indexed (Jan=0) — confusing Month is 1-indexed (Jan=1)
Date had both date and time — overloaded Separate classes: LocalDate, LocalTime, LocalDateTime
No timezone clarity ZonedDateTime, ZoneId, OffsetDateTime
Difficult formatting (SimpleDateFormat not thread-safe) DateTimeFormatter is immutable, thread-safe
Q92. Core Classes Overview
Class Stores Example
LocalDate Date only (year, month, day) 2024-06-15
LocalTime Time only (hour, min, sec, nanos) 14:30:00
LocalDateTime Date + Time (no timezone) 2024-06-15T14:30:00
ZonedDateTime Date + Time + Timezone 2024-06-15T14:30+05:30[Asia/Kolkata]
Instant Point in time (Unix epoch nanos) For timestamps, machine time
Period Date-based duration (years, months, days) P2Y3M5D
Duration Time-based duration (hours, seconds, nanos) PT3H30M
Q93. Common Operations
LocalDate today = [Link]();
LocalDate birthday = [Link](2000, [Link], 15);
LocalDate nextWeek = [Link](7);
LocalDate lastMonth = [Link](1);
boolean isLeap = [Link]();
// Period — between two dates
Period age = [Link](birthday, today);
[Link]([Link]() + " years old");
// Duration — between two times
LocalTime start = [Link](9, 0);
LocalTime end = [Link](17, 30);
Duration work = [Link](start, end); // PT8H30M
// Formatting
DateTimeFormatter fmt = [Link]("dd/MM/yyyy");
String formatted = [Link](fmt); // "15/06/2024"
LocalDate parsed = [Link]("15/06/2024", fmt);
// Timezone
ZonedDateTime mumbai = [Link]([Link]("Asia/Kolkata"));
Q94. Period vs Duration ■ TRICKY
Feature Period Duration
Measures Date-based (years, months, days) Time-based (hours, seconds, nanos)
Used with LocalDate LocalTime, LocalDateTime, Instant
DST-aware? Yes (months vary in length) No (fixed seconds)
Example P1Y2M3D = 1 year 2 months 3 days PT3H30M = 3 hours 30 min
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 19
12. Core Java — Tricky Output Questions
Q95. Output? (Post-increment trap) ■ TRICKY
int i = 0;
i = i++;
[Link](i); // 0
// i++ returns OLD value (0), then increments i to 1,
// then assigns the saved 0 back to i. Result: 0
Q96. Output? (Integer division vs floating point) ■ TRICKY
[Link](1/0); // ArithmeticException: / by zero
[Link](1.0/0); // Infinity
[Link](0.0/0); // NaN
[Link](-1.0/0); // -Infinity
Q97. Output? (Short-circuit vs bitwise) ■ TRICKY
int x = 5;
if (x > 3 || ++x > 5) { }
[Link](x); // 5 — || short-circuits, ++x never runs
int y = 5;
if (y > 3 | ++y > 5) { }
[Link](y); // 6 — | evaluates BOTH sides always
Q98. Output? (Overloading with null) ■ TRICKY
void print(Object o) { [Link]("Object"); }
void print(String s) { [Link]("String"); }
print(null); // "String" — most specific type wins
// If BOTH print(String) and print(Integer) exist:
// print(null) → compile error: ambiguous
Q99. Output? (Array covariance) ■ TRICKY
Object[] arr = new String[3];
arr[0] = "hello"; // OK
arr[1] = 42; // Compiles fine, but ArrayStoreException at runtime
// Array knows its actual type at runtime, rejects wrong type
Q100. Output? (equals without hashCode in HashMap) ■ TRICKY
class Key {
int id;
public boolean equals(Object o) { return o instanceof Key k && [Link] == id; }
// hashCode NOT overridden — uses [Link]() (identity-based)
}
Map map = new HashMap<>();
[Link](new Key(1), "hello");
[Link](new Key(1)); // null — different hashCodes → different buckets!
// ALWAYS override both equals() AND hashCode()
Q101. How to create an Immutable class?
public final class Employee { // 1. final class
private final String name; // 2. private final fields
private final List skills;
public Employee(String name, List skills) {
[Link] = name;
[Link] = new ArrayList<>(skills); // 3. defensive copy IN
}
public String getName() { return name; } // 4. no setters
public List getSkills() {
return [Link](skills); // 5. defensive copy OUT
}
}
Q102. Output? (Switch fall-through + continue) ■ TRICKY
for(int i=0; i<3; i++) {
switch(i) {
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 20
case 0: break;
case 1: continue; // skips rest of loop body for i=1
default: [Link]("default " + i);
}
[Link]("after " + i);
}
// Output: after 0 → default 2 → after 2
// (i=1: continue skips 'after 1' and the println inside switch)
Q103. Serialization & serialVersionUID
Converts object to/from byte stream. Class must implement Serializable. transient fields are excluded. serialVersionUID
ensures version compatibility — mismatch throws InvalidClassException.
class Employee implements Serializable {
private static final long serialVersionUID = 1L; // explicit version
private String name;
private transient String password; // excluded from serialization
}
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 21
13. Java Version Timeline — Java 9 to 26
Quick reference: what was added and what changed in each version. Not required in depth — just for awareness in
interviews.
Java 9 (2017)
• Module System (JPMS / Project Jigsaw) — modular JDK
• JShell — interactive REPL for Java
• [Link](), [Link](), [Link]() — immutable factory methods
• Stream: takeWhile(), dropWhile(), iterate() with predicate
• Optional: ifPresentOrElse(), stream()
• Interface private methods
• Process API improvements
• HTTP/2 Client (incubator)
Java 10 (2018)
• var keyword — local variable type inference
• [Link](), [Link](), [Link]()
• [Link]()
• Application Class-Data Sharing (performance)
• Thread-local handshakes
var list = new ArrayList(); // type inferred as ArrayList
Java 11 (2018 — LTS)
• String methods: isBlank(), strip(), lines(), repeat()
• [Link](), [Link]()
• var in lambda parameters: (var x, var y) -> x + y
• HTTP Client API (standard — replaces HttpURLConnection)
• Running single file: java [Link] (no javac needed)
• REMOVED: Java EE and CORBA modules from JDK
" hello ".strip(); // better than trim() — handles Unicode whitespace
Java 12 (2019)
• Switch Expressions (preview) — switch as expression
• [Link](), [Link]()
• Teeing Collector
Java 13 (2019)
• Text Blocks (preview) — multiline strings with """
• Switch Expressions (second preview)
Java 14 (2020)
• Switch Expressions (standard/final)
• Records (preview)
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 22
• Pattern Matching instanceof (preview): if (obj instanceof String s)
• Helpful NullPointerExceptions (NPE message shows which field was null)
// Old: if (obj instanceof String) { String s = (String) obj; ...}
// New: if (obj instanceof String s) { use s directly }
Java 15 (2020)
• Text Blocks (standard/final)
• Sealed Classes (preview)
• Records (second preview)
• Hidden Classes
String json = """
{"name": "Mihir",
"age": 21}
""";
Java 16 (2021)
• Records (standard/final) — immutable data carriers
• Pattern Matching instanceof (standard)
• [Link]() shorthand
• Vector API (incubator)
record Point(int x, int y) { }
// Auto-generates: constructor, getters, equals, hashCode, toString
Java 17 (2021 — LTS)
• Sealed Classes (standard) — restrict which classes can extend
• Pattern Matching in switch (preview)
• Random API improvements (RandomGenerator)
• Removed: Applet API, RMI Activation
• Strong encapsulation of JDK internals
sealed interface Shape permits Circle, Rectangle { }
record Circle(double radius) implements Shape { }
Java 18 (2022)
• Simple Web Server (jwebserver command)
• Code Snippets in Javadoc (@snippet tag)
• UTF-8 as default charset
• Pattern Matching switch (second preview)
• Vector API (third incubator)
Java 19 (2022)
• Virtual Threads (preview) — Project Loom — lightweight threads
• Structured Concurrency (incubator)
• Record Patterns (preview)
• Pattern Matching switch (third preview)
Java 20 (2023)
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 23
• Virtual Threads (second preview)
• Structured Concurrency (second incubator)
• Record Patterns (second preview)
• Scoped Values (incubator)
Java 21 (2023 — LTS)
• Virtual Threads (FINAL) — 1 JVM thread per task, not per OS thread
• Sequenced Collections — SequencedList, SequencedSet, SequencedMap
• Record Patterns (final)
• Pattern Matching switch (final)
• String Templates (preview)
• Unnamed Classes and Instance Main Methods (preview)
// Virtual Thread — replaces thread pools for I/O-bound work
try (var executor = [Link]()) {
[Link](() -> handleRequest());
}
Java 22 (2024)
• Unnamed Variables and Patterns: catch (Exception _) { }
• Launch Multi-File Programs
• Foreign Function & Memory API (final)
• String Templates (second preview)
• Stream Gatherers (preview)
Java 23 (2024)
• Primitive types in Patterns (preview)
• Module Import Declarations (preview)
• String Templates removed — redesign
• Markdown documentation comments
Java 24 (2025)
• Ahead-of-Time Class Loading & Linking (performance)
• Compact Object Headers (performance — reduced from 12 to 8 bytes)
• Quantum-resistant cryptography algorithms (ML-KEM, ML-DSA)
• Class-File API (final)
• Late Barrier Expansion for G1 GC
Java 25 (2025 — LTS)
• Stable Virtual Threads and structured concurrency
• Primitive types in patterns (final)
• Module Import Declarations (final)
• Value Objects (preview) — Project Valhalla begins landing
• Flexible Constructor Bodies (final)
Java 26 (2026 — expected)
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 24
• Project Valhalla features (Value Types) — objects without identity overhead
• Universal Generics (preview) — generics over primitives
• Continued Loom enhancements
• Note: Java 26 is in development — features may change
LTS versions (Long-Term Support, 8 years): 8, 11, 17, 21, 25. Use LTS for production. Most campus placement interviews
still focus on Java 8 features.
Core Java 8 — Interview Questions & Answers | Enhanced Edition Page 25