☕

Core Java

The Java fundamentals every interview starts with — OOP, Strings & Collections, Java 8+ features, exception handling, multithreading, JVM internals, and the DSA problems that show up alongside them.

DSA & Coding

Q

Search in rotated sorted array / linked list edge cases

intermediate

Tests whether you can adapt binary search to an array with one pivot break -- deciding which half is sorted at each step -- and separately handle the degenerate single-element and duplicate-boundary edge cases.

Q

Binary Tree: Preorder Traversal + Maximum Path Sum

advanced

Tests whether you know the max-path-sum recursion must track two different values per node -- the best downward path to return to the parent, and the best path-through-node to update a global max.

Q

Binary Search: Koko Eating Bananas / minimum eating speed

intermediate

Tests whether you recognize this as binary search over the answer space (eating speed), not over the array, using a feasibility check (hours needed at speed k) to drive the search.

Q

Quick Sort

intermediate

Tests whether you can implement the partition step correctly (pivot placement, pointer movement) and explain why worst-case O(n^2) happens on already-sorted input with a naive pivot choice.

Q

Anagram and its variations (DSA)

intermediate

Tests whether you reach for a frequency-count array/map instead of sorting each string, and can extend the same idea to grouping anagrams or finding anagram substrings in a larger string.

Q

Spiral printing of a matrix (DSA)

intermediate

Tests whether you can maintain four shrinking boundaries (top, bottom, left, right) and traverse them in order without off-by-one errors when rows or columns run out mid-cycle.

Q

Modify the solution to find all non-repeating elements while maintaining their order

intermediate

Tests whether you know a plain HashMap frequency count loses insertion order, and reach for a LinkedHashMap (or a second pass over the original array) to preserve it while still finding all count-1 elements.

Q

Merge two sorted arrays (nums1, nums2) in-place into nums1 without returning a new array (LeetCode 88 style)

intermediate

Tests whether you merge from the back (using the trailing empty space in nums1) instead of the front, since merging forward would overwrite elements you still need to compare.

Q

Find the number of trailing zeroes in the factorial of a given number (coding)

intermediate

Tests whether you know trailing zeroes come from factors of 10, which are always bottlenecked by the scarcer factor of 5, so you count multiples of 5, 25, 125... in n! rather than naively computing the full factorial, which overflows for even moderately sized n.

Q

Write a Java program to find words that can be typed using letters from only one row of a QWERTY keyboard

intermediate

Tests whether you map each letter to its keyboard row up front (via a lookup table), then check each word's letters all belong to the same row set, rather than doing a nested per-character row scan.

Q

Check whether two strings are anagrams

intermediate

Tests whether you reach for a character-frequency count (array or HashMap) compared between both strings in O(n), rather than sorting both strings and comparing, which works but costs an unnecessary O(n log n).

Q

Given an integer array, find all the prime numbers present in the array

intermediate

Tests whether you check primality with trial division up to sqrt(n) per element rather than the full range, and handle the 0/1/negative edge cases correctly.

Q

Complementary string pairs — count pairs where some permutation of their concatenation is a palindrome

advanced

Tests whether you reduce 'some permutation is a palindrome' to a character-parity bitmask per string, then count pairs whose masks are equal or differ by exactly one bit, instead of generating permutations.

Q

Cheapest flights within K stops (graph + BFS)

advanced

Tests whether you know plain Dijkstra fails here because it ignores the stop-count constraint, and reach for Bellman-Ford-style relaxation bounded to K+1 edges (or BFS layer by layer) instead.

Q

Implement a Sudoku solver — full running code, test cases checked

advanced

Tests whether you can implement backtracking with constant-time constraint checks (row/column/box bitmasks) rather than rescanning the board on every placement, since a naive solver times out on harder boards.

Q

Alien Dictionary — topological sort, with executable code

advanced

Tests whether you can derive character-ordering edges from adjacent word comparisons (first differing character only) and run Kahn's algorithm or DFS-based topological sort, including detecting an invalid/cyclic ordering.

Q

Find the median from a data stream, then optimize for approximate median in constant time and space

advanced

Tests whether you know the exact solution needs two balanced heaps (max-heap for the lower half, min-heap for the upper half), then can trade exactness for O(1) space using a streaming approximation like the P-square algorithm or reservoir sampling.

Q

Longest subarray where max minus min stays within a limit

advanced

Tests whether you use a sliding window with two monotonic deques (one tracking the window max, one the window min) to maintain both in amortized O(1) per step, instead of recomputing max/min on every window change.

Q

Number of Islands — then implement it in Java, without prior notice

intermediate

Tests whether you can translate the standard flood-fill (DFS/BFS from each unvisited land cell, marking visited) into working Java under time pressure, including correct grid bounds checking.

Q

Find the middle node of a linked list in one pass

intermediate

Tests whether you use the slow/fast pointer technique (fast moves two nodes per step) to find the middle in a single traversal, instead of counting length first and doing a second pass.

Q

Print the left view of a binary tree

intermediate

Tests whether you do a level-order (BFS) traversal and take the first node seen at each depth, or a depth-first traversal that only records a node the first time its depth is reached.

Q

Given a graph with V vertices and E edges, detect if it contains a cycle

intermediate

Tests whether you know cycle detection differs for directed graphs (track a recursion-stack/gray-node set, not just visited) versus undirected graphs (track the parent to avoid flagging the edge you just came from).

Q

Find the nth Fibonacci number for n <= 30

intermediate

Tests whether you notice the small n bound makes naive exponential recursion acceptable, but still know to mention memoization or iteration as the production-grade fix for larger n.

Q

Merge overlapping intervals given N intervals

intermediate

Tests whether you sort intervals by start time first, then merge in a single pass by comparing each interval's start against the current merged interval's end -- the sort is what makes the merge linear.

Q

Reverse a linked list in groups of k

advanced

Tests whether you can reverse each k-sized chunk in place while correctly re-linking the reversed chunk's tail to the next chunk's head, and handle a trailing group shorter than k per the stated rule.

Q

Find the longest common subsequence between two strings

intermediate

Tests whether you can build the 2D DP table where dp[i][j] extends by one on a character match or takes the max of dropping one character from either string on a mismatch.

Q

Check if a binary tree is height-balanced

intermediate

Tests whether you compute height and balance in a single bottom-up pass (returning -1 as an early-exit imbalance signal), instead of a naive solution that recomputes height from scratch at every node.

Q

Find the kth largest element in an unsorted array

intermediate

Tests whether you reach for a min-heap of size k or Quickselect (average O(n)) instead of fully sorting the array when only the kth largest value is needed.

Q

Move all zeroes to the end

intermediate

Tests whether you use a single-pass two-pointer swap (tracking the next non-zero insertion position) to move zeroes to the end in-place and O(n), instead of shifting elements repeatedly or allocating a new array.

Q

Longest common prefix

intermediate

Tests whether you compare characters column-by-column across all strings (or incrementally shrink a prefix candidate against each string) and stop at the first mismatch or shortest string, rather than comparing every pair of strings.

Q

Missing number in a consecutive array

intermediate

Tests whether you use the arithmetic-sum formula (or XOR of indices and values) to find the missing number in O(n) time and O(1) space, instead of sorting or using a hash set.

Q

Find the digital root of an integer

intermediate

Tests whether you know the digital root has a constant-time formula (1 + (n-1) mod 9) and can derive it from modular arithmetic, instead of only offering the repeated-summation loop.

Q

Coding: find the smallest missing positive integer (>0) in an unsorted array

advanced

Tests whether you achieve O(n) time and O(1) extra space by using the array itself as a hash table -- placing each value v at index v-1 via in-place swaps, then scanning for the first index that doesn't hold its expected value.

Q

Find the longest substring without repeating characters in Java

intermediate

Tests whether you use a sliding window with a character-index map, jumping the window's left edge directly past the previous occurrence of a repeated character instead of shrinking it one step at a time.

Q

Write a Java program to find duplicate characters and their frequency in a string

intermediate

Tests whether you build a single frequency map in one pass and then filter for counts greater than one, rather than comparing every character against every other character.

Q

Find the minimum-length subarray whose sum equals a given target.

intermediate

Tests whether you reach for a sliding window (shrinking from the left once the sum meets or exceeds target) for O(n) time on non-negative values, rather than the brute-force O(n^2) check of every subarray.

Q

Reverse a String without built-in methods.

intermediate

Tests whether you know to convert to a char array and swap from both ends inward (two-pointer, in-place), demonstrating you understand String's immutability means you can't reverse it in place directly.

Q

Find duplicate elements in an array.

intermediate

Tests whether you reach for a HashSet to track seen elements in a single O(n) pass, rather than a nested-loop O(n^2) comparison -- and whether you'd mention the in-place XOR/marking trick if the constraints demand no extra space.

Q

Check if a String is a palindrome.

intermediate

Tests whether you use a two-pointer comparison from both ends toward the middle for O(n) time and O(1) extra space, rather than reversing the string and comparing, which costs an unnecessary extra allocation.

Q

Implement an LRU Cache.

advanced

Tests whether you combine a HashMap (O(1) key lookup) with a doubly linked list (O(1) move-to-front/eviction) rather than a single data structure -- this is exactly what LinkedHashMap does internally, and knowing that shows you understand why the combination is necessary for true O(1) get/put.

Q

Implement the Producer-Consumer problem.

advanced

Tests whether you reach for a BlockingQueue (which handles wait/notify internally) as the production-grade answer, while also being able to implement the classic wait()/notify() version manually to show you understand what the queue abstracts away.

Q

Find the first non-repeating character.

intermediate

Tests whether you use a LinkedHashMap (or two passes with a frequency array) to track both counts and original order in O(n), rather than an O(n^2) approach that re-scans for each character.

Q

Detect a cycle in a linked list.

intermediate

Tests whether you reach for Floyd's cycle detection (slow/fast pointer) for O(n) time and O(1) space, rather than a HashSet of visited nodes, which works but costs O(n) extra space.

Q

Find the top K frequent elements.

intermediate

Tests whether you combine a frequency HashMap with a min-heap of size K for O(n log k) time, rather than sorting all elements by frequency (O(n log n)), which does unnecessary extra work when k is much smaller than n.

Inner Classes

JVM Internals & Memory

Q

What is the difference between Minor GC, Major GC, and Full GC?

intermediate

Tests whether you know exactly which memory regions each GC type actually sweeps.

Q

What is an OutOfMemoryError vs StackOverflowError?

intermediate

Tests whether you know these are triggered by two completely different memory regions filling up.

Q

G1 GC vs ZGC vs Shenandoah — when would you choose each?

advanced

Tests whether you know the pause-time and throughput tradeoffs across modern collectors, not just their names.

Q

Heap keeps growing even after a Full GC runs. How do you debug it?

advanced

Tests whether you recognize this as the classic memory-leak signature and know the heap-dump workflow to isolate it.

Q

Production throws OutOfMemoryError: Metaspace. What could cause it?

advanced

Tests whether you know Metaspace exhaustion usually points to classloader leaks, not regular object allocation.

Q

Java heap is stable, but overall process memory keeps growing. Why?

advanced

Tests whether you know to look past the heap entirely — direct ByteBuffers, Netty off-heap memory, or JNI leaks.

Q

Your application pauses frequently, but GC logs look completely normal. What's going on?

advanced

Tests whether you know JVM safepoints (biased lock revocation, deoptimization) can freeze threads independently of GC.

Q

What is Escape Analysis? Why is it useful?

advanced

Tests whether you know the JIT can allocate objects on the stack instead of the heap when it proves they never escape a method.

Q

What is the Parent Delegation Model in class loading, and why is it important?

intermediate

Tests whether you know why a class request always goes up the classloader hierarchy first, and what that prevents.

Q

How do you capture and analyze a heap dump using Eclipse MAT — what do you actually look for?

advanced

Tests whether you know the practical workflow: dominator tree, retained size, and finding the actual leak suspect.

Q

What is TLAB (Thread Local Allocation Buffer) and how does it improve allocation performance?

advanced

Tests whether you know how the JVM avoids lock contention on every single object allocation.

Q

What is GC ergonomics and how does the JVM auto-tune GC settings?

intermediate

Tests whether you know the JVM picks sensible defaults based on hardware and heap size without any flags at all.

Q

How many types of Garbage Collectors are there in Java?

intermediate

Tests whether you can name and roughly characterize the collectors -- Serial, Parallel, CMS (deprecated/removed), G1 (default since Java 9), ZGC, and Shenandoah -- and place them on the throughput-vs-pause-time spectrum rather than treating 'garbage collector' as one fixed algorithm.

Q

What are the different memory areas in JVM?

beginner

Tests whether you know the heap, stack, metaspace, and PC register layout and what lives where.

Q

What is Garbage Collection and how does it work?

intermediate

Tests whether you understand generational GC, reachability, and why Java doesn't need manual memory management.

Q

What is ClassLoader? Explain the delegation model.

intermediate

Tests whether you know why a class request is always delegated upward first, and what that prevents.

Q

What is the difference between WeakReference, SoftReference, and PhantomReference?

advanced

Tests whether you know these three reference types and how each affects when the GC is allowed to reclaim an object.

Q

How does the JIT compiler work?

advanced

Tests whether you understand how the JVM detects hot code paths and compiles them to native machine code at runtime.

Q

What improvements were introduced in Java 17 for Garbage Collection?

advanced

Tests whether you can name concrete GC advances landing around Java 17 -- G1 becoming the stable default with steadily reduced pause times, and ZGC maturing toward production readiness -- rather than a vague 'garbage collection got faster' without specifics.

Q

What is Code Cache and what happens when it fills up?

intermediate

The Code Cache stores JIT-compiled native code and has a fixed max size. Once full, the JVM stops compiling new methods and falls back to interpretation, gradually degrading performance until you raise -XX:ReservedCodeCacheSize.

Q

What does the -XX:+PrintCompilation flag show you?

intermediate

It prints every method as it gets JIT compiled — timestamp, compilation ID, tier level (1-4), and class/method name — useful for diagnosing which methods are hot and when deoptimization happens.

Q

What are the performance trade-offs between a 32-bit and 64-bit JVM?

advanced

32-bit has smaller pointers (less CPU cache pressure, faster for small short-lived apps) but caps heap around 3GB and only supports C1. 64-bit scales to available RAM and gets both C1+C2, but pointer overhead makes it not automatically faster for small apps.

Q

What is an escaping reference, and what are the ways to prevent your internal mutable state from leaking to callers?

advanced

Returning a live reference to an internal collection/object lets callers mutate your class's private state directly. Fix with: returning an iterator, a defensive copy, an immutable wrapper, a deep copy, a read-only interface, or hiding the implementation behind a Java Module boundary.

Q

How do you tune the String Pool for an application creating millions of unique strings?

advanced

The String Pool is a fixed-bucket hash table (65,536 buckets by default in Java 11+); millions of unique strings cause hash collisions and degrade lookup performance. Fix with -XX:StringTableSize=<prime number> sized for your actual string volume.

Q

What is String Deduplication in G1 GC and how is it different from the String Pool?

advanced

String Deduplication (-XX:+UseStringDeduplication with G1) finds identical strings already on the heap and makes them share one underlying char[] array, reducing memory — unlike the String Pool, which only applies to literals and doesn't touch strings created at runtime.

Q

Why should -Xms and -Xmx be set to the same value in production?

intermediate

If they differ, the JVM requests memory from the OS incrementally as needed, and G1 GC can even return unused heap to the OS — causing repeated OS-level allocation calls ("yo-yo" behavior). Setting them equal claims all memory upfront once.

Q

What are the most important JVM flags you should know for production tuning?

intermediate

-Xms/-Xmx (heap sizing), -XX:ReservedCodeCacheSize, -XX:+UseG1GC + -XX:MaxGCPauseMillis, -XX:+HeapDumpOnOutOfMemoryError, -XX:StringTableSize, -XX:NewRatio, -XX:SurvivorRatio, -XX:MaxTenuringThreshold — each controls a distinct part of JVM behavior worth knowing by name.

Q

Why should you never call System.gc() in production code?

beginner

It's only a suggestion the JVM is free to ignore — there's no guarantee it actually runs a collection. Meanwhile, if it does run, it pauses the application at a time you don't control, which can hurt response time unpredictably.

Q

Why is Object.finalize() dangerous, and what should you use instead?

intermediate

finalize() runs only when the GC decides to, with no guaranteed timing — a hung finalizer on one object can stall the GC for the whole JVM. It's deprecated since Java 9; use try-with-resources (AutoCloseable) for guaranteed, deterministic cleanup instead.

Q

What is Java Flight Recorder and how is it different from a heap dump?

advanced

JFR continuously records JVM events (allocations, GC, thread state, I/O) with typically under 1% overhead, giving you a timeline of behavior leading up to a problem — a heap dump is only a single point-in-time snapshot of live objects, with no history of how you got there.

Q

Why is naive Java benchmarking (System.nanoTime() around a loop) misleading?

intermediate

It measures code before JIT warm-up completes (so you're timing the slow interpreted version), can be skewed by a GC pause landing inside the measurement window, and the JIT can eliminate 'dead' code that computes a result nobody uses — all of which produce numbers that don't reflect real steady-state performance.

Q

What is JMH and what does it handle that a hand-rolled benchmark doesn't?

advanced

JMH (Java Microbenchmark Harness) automatically handles JIT warm-up iterations, runs multiple JVM forks for fresh state, computes statistical variance, and uses a Blackhole to prevent the JIT from eliminating your benchmarked code as dead code — all things a naive timing loop gets wrong.

Q

What is a DirectByteBuffer, and why can it cause OutOfMemoryError even when heap usage looks fine?

advanced

ByteBuffer.allocateDirect() allocates off-heap, native OS memory — invisible to normal heap monitoring tools. Exhausting it throws 'Direct buffer memory' OOM even with plenty of heap free; tune with -XX:MaxDirectMemorySize and check with jcmd VM.native_memory.

Q

Your Java process consumes 100% CPU — walk through diagnosing exactly which thread and method is responsible.

advanced

Use `top -H -p <pid>` to find the hot native thread ID, convert it to hex (`printf "%x"`), take a `jstack <pid>` dump, and search for that hex ID as `nid=0x...` in the dump — its stack trace shows the exact method spinning the CPU.

Q

Explain Java memory areas: Heap, Stack, Method Area and Program Counter (and Heap vs Stack).

intermediate

Tests whether you know the Heap holds all objects (shared, GC-managed), the Stack holds per-thread method frames and local primitives/references (private, auto-reclaimed on return), and the Method Area/Metaspace stores class metadata -- not just that 'objects go on the heap'.

Q

What is garbage collection and how does it work? What is the purpose of finalize()?

intermediate

Tests whether you describe GC as reachability analysis from GC roots (not simple reference counting, which can't handle cycles), and whether you flag finalize() as deprecated and unreliable -- it runs on no guaranteed schedule and modern code uses try-with-resources or Cleaner instead.

Q

What does jcmd VM.native_memory reveal that a heap dump cannot?

advanced

A heap dump only shows Java heap contents. `jcmd <pid> VM.native_memory summary` (with -XX:NativeMemoryTracking=summary enabled) shows the FULL JVM memory picture — heap, Metaspace, thread stacks, Code Cache, and GC structures — useful when a process uses far more OS memory than -Xmx suggests.

Q

Explain class metadata in the context of Java class loading.

intermediate

Tests whether you know class metadata (method tables, field layouts, constant pool, runtime type info) is stored in Metaspace after the classloader parses the .class file -- separate from instance data on the heap -- and that too many dynamically generated classes can exhaust Metaspace.

Q

Your Spring Boot app gets OOM-killed in Kubernetes even though heap usage looks fine — how do you size JVM memory correctly for a container?

advanced

By default the JVM may size its heap off the host's total RAM, not the container's cgroup limit, causing it to exceed the pod's memory limit. Fix with explicit -Xmx, or -XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0 (Java 10+), and remember total footprint = heap + Metaspace + Code Cache + thread stacks, not just -Xmx.

Q

What are the different types of OutOfMemoryError, and what does each one actually mean?

intermediate

'Java heap space' (heap full), 'GC overhead limit exceeded' (GC running constantly but barely reclaiming memory), 'Direct buffer memory' (off-heap exhausted), 'Metaspace' (class metadata space full), 'Unable to create new native thread' (OS thread limit hit) — each points to a genuinely different root cause and fix.

Q

What causes memory leaks in Java?

intermediate

Tests whether you know a Java 'leak' is really unintended reachability -- static collections that only grow, unclosed resources, listener/callback registrations never removed, or ThreadLocal values left behind in pooled threads -- not literal unmanaged memory like in C.

Q

What tools would you reach for to monitor a Java application's performance in production?

beginner

VisualVM and JMC/Flight Recorder for deep profiling, jcmd/jstat/jstack/jmap for quick command-line diagnostics, Eclipse MAT for heap dump analysis, and Prometheus+Grafana (or Datadog/Dynatrace) for continuous production metrics and alerting.

Q

Why can OutOfMemoryError happen even when garbage collection is enabled?

advanced

Tests whether you know GC can only reclaim unreachable objects -- if live references still exist (a growing cache, a leaking listener list), the GC runs successfully every time but frees nothing useful, and the heap fills regardless.

Q

What is GraalVM and how does its Native Image differ from a standard JVM?

advanced

GraalVM is an alternative JVM with its own JIT compiler (written in Java) and a Native Image tool that Ahead-of-Time compiles your whole app into a standalone executable — near-instant startup and low memory, but no runtime JIT profiling means lower peak throughput, and reflection/dynamic class loading need to be declared upfront.

Q

How would you investigate unusually long GC pauses, including pauses that grow after a new release?

advanced

Tests whether you'd pull GC logs (-Xlog:gc*) to check for full GCs vs young-gen collections, correlate pause growth with a recent change in allocation rate or object retention, and consider whether the collector (G1 vs ZGC) matches the new workload's latency profile.

Q

30 GB heap with a 10 ms pause budget: G1 or ZGC, and why?

advanced

Tests whether you pick ZGC -- G1's pause times scale with heap size and live-set complexity, typically landing in tens-to-hundreds of ms on a 30GB heap, while ZGC's concurrent, region-based collection keeps pauses sub-millisecond regardless of heap size, which is the only way to reliably hit a 10ms budget.

Java Basics & OOP

Q

What is the difference between JDK, JRE, and JVM?

beginner

Tests whether you understand the three nested layers of the Java platform and what each one is actually responsible for.

Q

Explain the 4 pillars of OOP with real-world examples.

beginner

Checks whether you can explain encapsulation, abstraction, inheritance, and polymorphism with concrete examples, not just definitions.

Q

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

beginner

Tests your understanding of reference equality versus logical equality, and where each one silently trips people up.

Q

What is method overloading vs method overriding?

beginner

Tests whether you know compile-time vs runtime polymorphism and the rules that govern each.

Q

What is the difference between abstract class and interface?

beginner

Tests whether you know when to use each, especially after Java 8 added default and static methods to interfaces.

Q

Explain the 'static' keyword — static variable, method, block, class.

beginner

Tests whether you understand what 'belongs to the class, not the instance' actually means in memory and execution order.

Q

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

beginner

A classic trick question — tests whether you know Java is always pass-by-value, even for objects, and why that still confuses people.

Q

What is autoboxing and unboxing?

beginner

Tests whether you know how Java silently converts between primitives and wrapper classes, and where that costs performance.

Q

What is the diamond problem and how does Java 8 solve it with default methods?

advanced

Tests whether you understand multiple inheritance ambiguity and the specific resolution rules Java applies for default methods.

Q

Explain how 'instanceof' works and what pattern matching for instanceof (Java 16) does.

advanced

Tests whether you know the classic instanceof check plus the newer syntax that eliminates the redundant cast afterward.

Q

Does the final keyword make an object immutable?

beginner

No — final only prevents reassigning the reference itself; the object's internal state can still be mutated through its setters. True immutability requires the class itself to have no mutating methods.

Q

Why should you never use double for financial calculations?

intermediate

Binary floating point can't represent most decimal fractions exactly — `0.1 + 0.2` prints `0.30000000000000004`. Use BigDecimal with the String constructor (`new BigDecimal("0.1")`, never the double constructor) for exact decimal arithmetic; it's 5-10x slower but correctness matters more for money.

Java Fundamentals

Q

Why is Java not considered a purely Object-Oriented language?

beginner

Java has 8 primitive types (int, char, boolean, etc.) that are not objects — a truly pure OO language (like Smalltalk) treats everything, including numbers, as an object. Java also supports static members and methods that belong to a class rather than an instance, which is another departure from pure OO design.

Q

How does a Java program actually run, from source file to execution?

beginner

The .java source is compiled by javac into platform-independent .class bytecode; the JVM's class loader loads that bytecode, the bytecode verifier checks it for safety, and the execution engine (interpreter + JIT compiler) then runs it, translating hot bytecode into native machine code on the fly.

Q

Why is Java called a platform-independent language?

beginner

Java source code compiles to bytecode, not native machine code — that bytecode runs unchanged on any device with a compatible JVM, since the JVM (not the OS) is what actually translates it into native instructions. "Write once, run anywhere" refers to the bytecode being portable, not the JVM itself, which is platform-specific.

Q

Why doesn't Java use pointers the way C/C++ does?

beginner

Java uses references instead of raw pointers — a reference lets you access an object but never lets you perform pointer arithmetic or directly manipulate a memory address. This removes an entire class of bugs (dangling pointers, buffer overruns, memory corruption) and is what makes automatic garbage collection safe, since the JVM can always track exactly which references point to which objects.

Core Java Fundamentals

Q

Explain the different types of polymorphism, especially runtime polymorphism, with an example.

intermediate

Tests whether you connect runtime polymorphism to dynamic method dispatch via the vtable -- the JVM resolves the overridden method based on the actual object type at runtime, not the reference type at compile time.

Q

Can we overload a method by changing only its return type?

intermediate

Tests whether you know overload resolution is based solely on the method signature (name + parameter types), so return type alone causes a compile error -- not ambiguity, because the compiler can't distinguish the two methods at all.

Q

Can we overload the main() method? Which one does the JVM execute?

intermediate

Tests whether you know main() can be overloaded like any static method, but the JVM launcher only ever invokes the exact signature public static void main(String[] args) by reflection -- the others are just ordinary overloads you'd have to call yourself.

Q

Difference between this and super keywords.

intermediate

Tests whether you know this refers to the current object instance (used for disambiguating fields/constructor chaining within the class), while super refers to the immediate parent class (used to access parent members or invoke the parent constructor) -- and that both must be the first statement when chaining constructors.

Q

How do you create and handle custom exceptions?

intermediate

Tests whether you know to extend Exception (checked, forces callers to handle or declare) vs RuntimeException (unchecked), and whether you preserve the original cause via the constructor that takes a Throwable instead of swallowing the stack trace.

Q

Difference between BufferedInputStream and BufferedOutputStream

intermediate

Tests whether you know BufferedInputStream wraps a raw input stream to reduce the number of actual read() system calls by pulling larger chunks into an internal buffer, while BufferedOutputStream batches writes into its buffer and only flushes to the underlying stream when full or explicitly flushed.

Q

Difference between == and .equals()?

intermediate

Tests whether you know == compares references (or primitive values) while .equals() compares logical/content equality as defined by the class -- and that unboxed Integer caching (-128 to 127) is the classic trap that makes == appear to 'work' until it doesn't.

Q

Difference between JVM, JRE and JDK?

intermediate

Tests whether you know the containment hierarchy: JVM executes bytecode, JRE wraps the JVM plus core libraries to run programs, and JDK wraps the JRE plus the compiler and dev tools needed to build programs -- not just three interchangeable acronyms.

Q

What are Filter Streams?

intermediate

Tests whether you know FilterInputStream/FilterOutputStream are the decorator-pattern base classes that wrap another stream to add behavior (buffering, data type conversion, checksums) without changing the underlying stream's interface -- the mechanism behind classes like BufferedInputStream and DataInputStream.

Q

Explain the String Pool.

intermediate

Tests whether you know the String Pool is a special heap region (part of the heap since Java 7, not PermGen) that interns string literals so identical literals share one object -- and that new String("x") deliberately bypasses it unless you call intern().

Q

What is Serialization, and where have you used it?

intermediate

Tests whether you understand serialization converts an object graph into a byte stream for storage or transmission (via implementing Serializable), and whether you can name a real use case -- caching, session replication, or message passing between JVMs -- instead of only reciting the mechanism.

Q

Which encryption/hashing mechanism do you use for storing passwords?

intermediate

Tests whether you know passwords must be hashed with a slow, salted algorithm designed for this purpose (bcrypt, scrypt, or Argon2) rather than encrypted (which is reversible) or hashed with a fast general-purpose function like plain SHA-256, which is vulnerable to brute-force and rainbow-table attacks.

Q

Why is String immutable in Java?

intermediate

Tests whether you connect immutability to String Pool safety (sharing literals would break if one reference could mutate another), hashcode caching for fast HashMap lookups, and thread-safety without synchronization -- not just 'because it's final'.

Q

Why must equals() and hashCode() be consistent? What happens if they are implemented incorrectly?

intermediate

Tests whether you know hash-based collections rely on the contract that equal objects must produce equal hash codes -- break it and a HashMap/HashSet will silently fail to find an object you just inserted because it lands in the wrong bucket.

Q

What is an enum type? How do you compare two enum values?

intermediate

Tests whether you know Java enums are full classes with a fixed set of singleton instances, so comparing them with == is always safe and preferred over equals() -- since each enum constant is guaranteed to be a single shared instance, unlike ordinary objects.

Q

Explain Lombok and its advantages

intermediate

Tests whether you know Lombok generates boilerplate (getters, setters, constructors, equals/hashCode, builders) at compile time via annotation processing, and whether you're aware of its trade-off -- less code to maintain versus 'magic' that can obscure what's actually being generated for newcomers reading the class.

Q

Difference between abstraction and interface

intermediate

Tests whether you separate the concept from the construct -- abstraction is the design principle of hiding implementation details behind a simpler contract, while an interface is one specific Java language mechanism for achieving it, alongside abstract classes.

Q

What is Method Hiding in Java? How would you implement it?

intermediate

Tests whether you know static methods aren't polymorphic -- redeclaring a static method with the same signature in a subclass hides the parent's version rather than overriding it, so which one runs is resolved by the reference's compile-time type, not the object's runtime type.

Q

What is abstraction? Explain with a real-world/project example. When would you use an abstract class instead of a normal class?

intermediate

Tests whether you can justify an abstract class choice concretely -- when you want to share common state or partial implementation across subtypes while still forcing them to fill in specific behavior -- rather than defaulting to abstract classes out of habit when a normal class with composition would do.

Q

What is a static class? Why do we need it? Where have you used it (Helper/Utility example)?

intermediate

Tests whether you know a static nested class doesn't hold an implicit reference to its enclosing instance, which is why utility/helper classes are made static -- they don't need outer-instance state, and keeping that reference would just waste memory and allow accidental coupling.

Q

What is the difference between final, finally, and finalize()?

intermediate

Tests whether you keep the three apart despite the similar spelling -- final is a modifier preventing reassignment/overriding/subclassing, finally is the block that always runs after try/catch regardless of outcome, and finalize() is a deprecated Object method the GC used to call before reclaiming an object, with no execution guarantee.

Q

What is the difference between composition and inheritance? When would you prefer one over the other?

advanced

Tests whether you default to 'favor composition over inheritance' for the right reason -- composition keeps classes loosely coupled and avoids the fragile base class problem, while inheritance is justified only for genuine is-a relationships where subtypes must be substitutable for the base.

Q

Aggregation vs composition?

intermediate

Tests whether you know both describe a has-a relationship, but aggregation is a weak association where the contained object can outlive the container (a Department holding Employees that exist independently), while composition is a strong ownership relationship where the contained object's lifecycle is bound to the container's.

Q

Why should an immutable class generally be final?

advanced

Tests whether you know a non-final immutable class can be subclassed, and that subclass can override methods to introduce mutable state or behavior that breaks the immutability contract callers rely on -- sealing the class with final is what actually guarantees every instance behaves immutably.

Q

What is a defensive copy and why is it needed?

advanced

Tests whether you know returning or storing a direct reference to a mutable field (like a Date or array) lets external code mutate your object's internal state without going through its API -- a defensive copy on the way in or out closes that hole and is essential for genuinely immutable classes.

Q

What is the transient keyword?

intermediate

Tests whether you know transient marks a field to be skipped during default Java serialization, used for fields that are derived, sensitive, or simply not serializable (like a Thread or Socket reference) -- the field survives in memory but comes back as its default value after deserialization.

Collections

Q

What is the difference between ArrayList and LinkedList — when to use which?

intermediate

Tests whether you connect the right structure to the right access pattern -- ArrayList's contiguous array gives O(1) random access but O(n) middle inserts, while LinkedList's node chain gives O(1) inserts/removes at known positions but O(n) indexed access, with the node overhead usually making ArrayList the better default anyway.

Q

What is the difference between Comparable and Comparator?

intermediate

Tests whether you know Comparable defines a class's single natural ordering via compareTo() implemented on the class itself, while Comparator defines an external, pluggable ordering you can swap at call time -- and that you need Comparator the moment you want more than one sort order for the same type.

Q

Why use HashMap instead of nested loops?

intermediate

Tests whether you connect HashMap's O(1) average lookup to collapsing an O(n^2) nested-loop comparison into an O(n) single pass -- trading a bit of memory for hash-bucket lookups instead of re-scanning the second collection for every element of the first.

Q

What changed in HashMap in Java 8 compared with previous versions?

advanced

Tests whether you know Java 8 introduced bucket treeification (converting a long collision chain into a red-black tree once it crosses a threshold, dropping worst-case lookup from O(n) to O(log n)) and changed the hash spreading function, rather than assuming HashMap's internals stayed the same across versions.

Q

If two threads access and modify the same HashMap concurrently, what can go wrong?

advanced

Tests whether you know beyond simple data corruption, concurrent resizing on a plain HashMap can create a circular reference in a bucket's linked list, putting a later get() into an infinite loop that pegs CPU -- the classic reason HashMap is explicitly documented as not thread-safe.

Q

How do you make a LinkedList synchronized?

intermediate

Tests whether you reach for Collections.synchronizedList(new LinkedList<>()) to get a thread-safe wrapper, and whether you know you still need to manually synchronize on the returned list when iterating, since the wrapper only synchronizes individual method calls.

Q

When does a HashMap bucket become a Red-Black Tree?

advanced

Tests whether you know the exact thresholds -- a bucket treeifies once its chain hits 8 entries AND the table has at least 64 buckets (otherwise it resizes instead), and untreeifies back to a linked list once it drops to 6 -- not just the vague idea that 'long chains become trees.'

Q

A HashMap key's hashCode changes after insertion. What does get() return for that key?

advanced

Tests whether you know HashMap computes and caches the bucket index at insertion time, so a mutated key's new hashCode won't match where it's actually stored -- get() with the mutated key returns null because it looks in the wrong bucket entirely.

Q

How does IdentityHashMap differ from a normal HashMap?

intermediate

Tests whether you know IdentityHashMap uses reference equality (==) instead of .equals()/hashCode() for key comparison, so two distinct-but-equal objects are treated as different keys -- a niche tool for identity-based caching, not a general-purpose map.

Q

How can null be handled in a TreeSet?

intermediate

Tests whether you know a TreeSet throws NullPointerException on adding null because its ordering relies on compareTo()/Comparator, which can't compare against null -- unless you supply a custom Comparator that explicitly defines null's position.

Q

What is a cache map in Java collections?

intermediate

Tests whether you connect this to LinkedHashMap's removeEldestEntry() hook (the classic DIY LRU building block) rather than treating 'cache map' as a built-in JDK type -- Java has no first-class cache collection out of the box.

Q

Difference between List, Set and Map.

intermediate

Tests whether you articulate the core contract distinctions -- List is ordered and allows duplicates, Set enforces uniqueness via equals()/hashCode(), and Map stores key-value pairs with unique keys -- not just 'they're all collections'.

Q

HashMap has 1 million entries. Performance is degrading. Why, and how would you resolve it?

advanced

Tests whether you check the initial capacity/load factor first -- an undersized initial capacity forces repeated resize-and-rehash cycles as the map grows to a million entries, and the fix is pre-sizing the map to its expected final size instead of letting it grow incrementally from the default 16.

Q

Difference between Collection and Collections.

intermediate

Tests whether you know Collection is the root interface of the collections hierarchy, while Collections is a utility class of static helper methods (sort, synchronizedList, unmodifiableList) -- a naming trap interviewers use to check real familiarity vs memorized terms.

Q

How does HashSet work internally? What happens when you add an object to a HashSet?

intermediate

Tests whether you know HashSet is a thin wrapper around a HashMap<E, Object> where your element becomes the key and a constant dummy object is the value -- add() computes hashCode(), finds the bucket, and uses equals() to check for an existing duplicate before inserting.

Q

Difference between HashMap, LinkedHashMap and TreeMap.

intermediate

Tests whether you map each to its ordering guarantee and backing structure: HashMap gives no order (bucket array + hashing), LinkedHashMap preserves insertion (or access) order via an internal doubly-linked list, and TreeMap keeps sorted order via a red-black tree, trading O(1) for O(log n).

Q

Why does HashMap allow one null key?

intermediate

Tests whether you know HashMap special-cases the null key by always placing it in bucket 0 (since hashCode() can't be called on null), and that only one null key can exist because a Map's keys must be unique -- a deliberate design choice, not an accident of the hashing algorithm.

Q

Difference between HashSet, LinkedHashSet and TreeSet.

intermediate

Tests whether you connect each Set variant to the Map it's built on underneath -- HashSet/HashMap, LinkedHashSet/LinkedHashMap, TreeSet/TreeMap -- so the same ordering and performance trade-offs apply directly.

Q

Why doesn't ConcurrentHashMap allow null keys/values?

advanced

Tests whether you know the reason is concurrency-specific ambiguity -- in a map accessed by multiple threads, get(key) returning null could mean either 'the key isn't present' or 'the key maps to null,' and that ambiguity is unresolvable without external locking, which defeats the point of a concurrent collection.

Q

Why can an ArrayList become a performance problem with a very large dataset?

advanced

Tests whether you connect it to resize cost (growing by 50% and copying the whole backing array), O(n) insert/remove in the middle, and memory overhead from over-allocated capacity -- not just 'arrays are slow'.

Q

ArrayList vs Vector?

intermediate

Tests whether you know Vector is a legacy class that synchronizes every method (making it thread-safe but slower even when uncontended), while ArrayList is unsynchronized by default -- and that Vector's per-method locking still doesn't make compound operations like check-then-add atomic, so it's rarely the right choice over ArrayList plus explicit synchronization or a concurrent collection.

Q

Implement a custom Iterator and a custom Exception

intermediate

Tests whether you correctly implement Iterable/Iterator's hasNext()/next() contract (including throwing NoSuchElementException when exhausted) and can design a custom exception that extends the right base class for its intended checked/unchecked handling.

Q

Is ConcurrentHashMap fail-fast?

advanced

Tests whether you know ConcurrentHashMap's iterators are weakly consistent, not fail-fast -- they never throw ConcurrentModificationException and may or may not reflect modifications made during iteration, a deliberate trade-off for safe concurrent access instead of the strict fail-fast guarantee HashMap's iterator gives.

Multithreading & Concurrency

Q

Synchronization vs Concurrent Collections — when & why?

advanced

Tests whether you know wrapping a collection with Collections.synchronizedX() locks the whole structure on every operation (and still needs external synchronization for iteration), while java.util.concurrent collections use finer-grained or lock-free techniques internally -- so you default to concurrent collections for throughput under real contention, not synchronized wrappers.

Q

What is the difference between Project Loom and traditional threads?

advanced

Tests whether you understand virtual threads are cheap, JVM-scheduled, and unmount from the carrier thread on blocking I/O, versus platform threads which map 1:1 to OS threads and are expensive to spawn.

Q

Why do we need async and await? What happens when you call an asynchronous API? Difference between async programming and multithreading?

intermediate

Tests whether you distinguish async (non-blocking, often single-threaded via an event loop or continuation) from multithreading (actual parallel execution), and that calling an async API returns a handle/promise immediately rather than blocking the caller.

Q

Why do Virtual Threads become pinned and lose scalability?

advanced

Tests whether you know synchronized blocks and native calls can pin a virtual thread to its carrier thread.

Q

What is structured concurrency in Java 21+ and why is it better than raw CompletableFuture chains?

advanced

Tests whether you know how it ties a group of subtasks' lifetimes together for cleaner cancellation and error handling.

Q

Why are exceptions inside CompletableFuture chains often missed silently?

advanced

Tests whether you know an unhandled exception in a chain just completes the future exceptionally, with nothing logged unless you check.

Q

ConcurrentHashMap is thread-safe, yet race conditions can still exist in code that uses it. Why?

advanced

Tests whether you know thread-safety of individual operations doesn't make compound check-then-act sequences atomic.

Q

Why can increasing the thread pool size actually reduce application performance?

advanced

Tests whether you know excessive threads can increase context-switching overhead and contention beyond a certain point.

Q

What is the difference between synchronized, ReentrantLock, and StampedLock?

advanced

Tests whether you know the tradeoffs in fairness, interruptibility, and read/write optimization across the three.

Q

What is the difference between CountDownLatch, CyclicBarrier, and Semaphore?

advanced

Tests whether you know these three synchronization tools solve genuinely different coordination problems.

Q

How does ForkJoinPool differ from a regular ThreadPoolExecutor?

advanced

Tests whether you know work-stealing is what makes ForkJoinPool efficient for divide-and-conquer tasks specifically.

Q

What happens when you submit too many tasks to a ThreadPoolExecutor — what are the rejection policies?

advanced

Tests whether you know the four built-in RejectedExecutionHandler strategies and when each is appropriate.

Q

What is a race condition and how is it different from a data race?

advanced

Tests whether you know these overlapping-sounding terms actually describe two distinct classes of concurrency bug.

Q

A ThreadLocal variable in your app is causing a memory leak. How does that happen, and how do you fix it?

advanced

Tests whether you know pooled threads never die, so a ThreadLocal never cleared keeps leaking across every reused thread.

Q

What is multithreading? When would you use multiple threads in a real application? How is it different from asynchronous programming?

advanced

Tests whether you separate the two correctly -- multithreading is about using multiple threads of execution (often blocking), while asynchronous programming is about non-blocking composition of work that may run on far fewer threads (e.g. an event loop) -- so 'async' doesn't automatically mean 'multithreaded.'

Q

What is the difference between synchronized method and synchronized block?

intermediate

Tests whether you know a synchronized method locks on the entire object (or the Class object for static methods) for its whole duration, while a synchronized block lets you lock on a specific object and scope the critical section as narrowly as possible, reducing contention by not holding the lock over unrelated code.

Q

wait vs sleep. How can incorrect usage lead to deadlocks?

advanced

Tests whether you know sleep() holds any locks the thread owns for its entire duration, so sleeping while holding a lock another thread needs can create a deadlock-like stall, while wait() correctly releases the monitor -- and whether you know an improperly guarded wait() (missing the notify, or checking the condition outside a loop) can leave a thread waiting forever.

Q

What is the difference between a Thread and a Process?

beginner

Tests whether you understand shared vs isolated memory space and why threads are cheaper to create.

Q

What is the difference between wait(), notify(), and notifyAll()?

intermediate

Tests whether you understand Java's low-level thread coordination primitives and the monitor lock they require.

Q

Future vs CompletableFuture. Give a real-life example of where it is used.

intermediate

Tests whether you know Future only supports blocking get() with no way to chain or compose callbacks, while CompletableFuture supports non-blocking composition (thenApply, thenCombine) -- e.g. fanning out calls to multiple downstream services and combining results without blocking a thread on each.

Q

What is a deadlock? How can you detect and prevent it?

intermediate

Tests whether you know the four necessary conditions for deadlock and practical strategies to avoid them.

Q

Why can CompletableFuture still block your application?

advanced

Tests whether you know calling .get() or .join() defeats the async design by blocking the calling thread, and that blocking calls inside callback stages (thenApply/thenCompose) without specifying an executor can starve the shared ForkJoinPool.commonPool().

Q

Difference between ExecutorService, ForkJoinPool, and a plain Thread

intermediate

Tests whether you know ForkJoinPool is a work-stealing ExecutorService variant built for divide-and-conquer recursive tasks, distinct from a general-purpose ExecutorService's fixed task queue and from manually managing raw Thread objects.

Q

What is the volatile keyword in Java?

intermediate

Tests whether you know volatile guarantees visibility, not atomicity — one of the most commonly misunderstood keywords.

Q

What is ExecutorService? How is it better than creating raw threads?

intermediate

Tests whether you know why managed thread pools beat manually creating and managing Thread objects in production code.

Q

How do you make a HashMap thread-safe without using ConcurrentHashMap?

intermediate

Tests whether you know Collections.synchronizedMap() wraps every operation in a single lock (coarser and slower than ConcurrentHashMap's striped locking) and that manual external synchronization is also required around iteration.

Q

Difference between Runnable and Callable.

intermediate

Tests whether you know Runnable.run() returns nothing and can't throw checked exceptions, while Callable<V>.call() returns a value and can throw checked exceptions -- which is exactly why ExecutorService.submit() with a Callable gives you a Future you can inspect for both result and failure.

Q

What is a thread-safe Singleton? Implement double-checked locking.

advanced

Tests whether you can correctly write the volatile + double-checked-locking pattern, a classic concurrency coding question.

Q

Difference between start() and run().

intermediate

Tests whether you know start() allocates a new OS/native thread and the JVM eventually calls run() on it, while calling run() directly just executes the code synchronously on the current thread -- a classic 'runs but doesn't actually thread' bug.

Q

Difference between @Async and a manually managed thread pool in Spring

advanced

Tests whether you know @Async is a proxy-based abstraction that still delegates to an underlying Executor (often the default SimpleAsyncTaskExecutor, which doesn't pool), so misconfiguring it can silently spawn an unbounded thread per call unlike an explicitly sized pool.

Q

Difference between wait(), sleep() and join().

intermediate

Tests whether you know wait() releases the object's monitor and must be called inside synchronized code (used for inter-thread signaling), sleep() holds any locks it has and just pauses the current thread, and join() blocks the calling thread until the target thread finishes.

Q

What happens internally when 100 tasks are submitted to a ThreadPoolExecutor with only 8 worker threads?

advanced

Tests whether you know the first 8 tasks run immediately while the rest queue up to the work queue's capacity, and that further submissions trigger the configured RejectedExecutionHandler once both the pool and queue are full.

Q

What is the Java Memory Model (JMM)? Explain happens-before.

advanced

Tests whether you understand the formal rules that govern visibility and ordering across threads — deep concurrency territory.

Q

What is CompletableFuture? How does it differ from Future?

advanced

Tests whether you know how to chain and combine async operations rather than blocking with Future.get().

Q

volatile vs AtomicInteger

intermediate

Tests whether you know volatile only guarantees visibility of single reads/writes, not atomicity of compound operations like increment, while AtomicInteger uses CAS to make read-modify-write atomic.

Q

What is synchronization in Java?

intermediate

Tests whether you describe it as mutual exclusion via a monitor lock on an object, enforcing that only one thread executes a critical section at a time -- and that it also establishes a happens-before relationship for visibility, not just atomicity.

Q

Instruction Reordering & Memory Barriers

advanced

Tests whether you know the compiler, JIT, and CPU are all free to reorder instructions that have no data dependency on each other for performance, and that memory barriers (which volatile and synchronized insert) are the explicit fences that prevent specific reorderings across a thread-visibility boundary.

Q

Difference between a process and a thread.

intermediate

Tests whether you know a process has its own isolated memory space and is heavier to create/switch, while threads within a process share the same heap and address space, making communication cheap but requiring explicit synchronization.

Q

Atomicity & Race Conditions — check-then-act, read-modify-write, and why count++ isn't safe

advanced

Tests whether you can decompose count++ into its actual three steps (read, increment, write) and explain that two threads interleaving between those steps can both read the same value and both write back the same increment, silently losing an update -- the canonical read-modify-write race.

Q

volatile vs synchronized: when would you use volatile?

intermediate

Tests whether you know volatile only guarantees visibility (reads always see the latest write) and prevents instruction reordering around it, but gives no atomicity for compound operations -- so it's right for simple flags/status fields, not for counters or anything needing read-modify-write.

Q

synchronized & Monitors — intrinsic locks, owner/entry set/wait set, reentrant semantics

advanced

Tests whether you know the monitor model precisely -- one thread owns the lock at a time, other lock-seekers queue in the entry set, threads that called wait() move to the wait set until notified, and the owning thread can re-acquire its own lock without blocking, which is what makes nested synchronized calls on the same object safe.

Q

Difference between synchronized, Lock and Atomic classes.

intermediate

Tests whether you place each on the right trade-off curve: synchronized is simple JVM-managed mutual exclusion, Lock (ReentrantLock) adds tryLock/fairness/interruptibility at the cost of manual unlock discipline, and Atomic classes use lock-free CAS for the fastest path when only a single variable's atomicity matters.

Q

Why are immutable objects useful in multithreaded applications?

intermediate

Tests whether you know an object whose state can't change after construction is inherently thread-safe -- no synchronization is needed because there's no mutation for threads to race on.

Q

What is a deadlock? How do you identify and prevent it in production?

advanced

Tests whether you'd pull a thread dump and look for the 'Found one Java-level deadlock' block showing the circular lock-wait chain, and whether you know prevention means consistent lock ordering across the codebase rather than retry-and-hope.

Q

What is ExecutorService?

intermediate

Tests whether you describe it as the thread-pool abstraction that decouples task submission from thread lifecycle management, letting you reuse a bounded pool of threads instead of paying the cost of creating a new OS thread per task.

Q

When would you choose AtomicInteger over synchronized?

intermediate

Tests whether you know AtomicInteger's lock-free CAS loop outperforms synchronized under high contention for simple single-variable updates, while synchronized is still needed when multiple related fields must change together atomically.

Q

What is a race condition?

intermediate

Tests whether you define it precisely as the outcome depending on the unpredictable timing/interleaving of concurrent thread execution on shared mutable state -- not just 'two threads running at the same time'.

Q

Difference between Thread class and Runnable interface

intermediate

Tests whether you know implementing Runnable (and passing it to a Thread) decouples the task from Java's single-inheritance limit and lets the same task be reused across executors, unlike extending Thread directly.

Q

What happens if an exception occurs inside an ExecutorService task?

advanced

Tests whether you know submit() swallows the exception into the returned Future until you call get() (which rethrows it wrapped in ExecutionException), while execute() with a Runnable sends it straight to the thread's uncaught exception handler -- a silent-failure trap if you never check the Future.

Q

Analyze a multithreading scenario involving synchronized instance vs static methods

advanced

Tests whether you know a synchronized instance method locks on 'this' (so different instances don't block each other), while a synchronized static method locks on the Class object (shared across every instance) -- mixing the two in a scenario means an instance-method call and a static-method call can run concurrently on the same data without ever actually excluding each other.

Q

An @Async method throws an exception. Nobody catches it. What happens?

advanced

Tests whether you know an exception from a void @Async method is swallowed by the default AsyncUncaughtExceptionHandler and logged, not propagated to the caller, so you need a custom handler or a Future-returning method to observe it.

Q

What happens when your thread pool is completely exhausted?

advanced

Tests whether you know new tasks queue up (if a bounded queue has room) or get rejected via the RejectedExecutionHandler once both the pool and queue are full -- and that an unbounded queue just defers the problem into an OOM instead of solving it.

Q

Why can creating too many threads make an application slower?

advanced

Tests whether you connect it to context-switching overhead and cache thrashing once thread count exceeds available cores by a wide margin, plus the memory cost of each thread's stack -- more threads than the workload can parallelize just adds scheduling overhead.

Q

What happens to MDC/request context when work moves from one thread to another?

advanced

Tests whether you know MDC is backed by a ThreadLocal, so context set on the request thread doesn't automatically appear on a worker thread -- it must be explicitly copied (or propagated via a TaskDecorator) when handing off work.

Q

How would you handle 10,000 concurrent requests in a Java backend?

advanced

Tests whether you reach for non-blocking I/O (WebFlux/Netty) or Java 21 virtual threads to decouple concurrent requests from a 1:1 OS-thread cost, rather than assuming you can just size a traditional thread pool to 10,000.

Q

A thread is stuck in BLOCKED state. How will you identify and fix it?

advanced

Tests whether you'd take a thread dump and look for the thread holding the monitor that the BLOCKED thread is waiting on, then trace why that holder never releases it (often a lock held across a slow I/O or network call).

Q

How would you make a Java API thread-safe?

intermediate

Tests whether you default to avoiding shared mutable state first (stateless beans, immutable DTOs, request-scoped data) before reaching for synchronization primitives, since the cheapest thread-safety is state you never had to protect.

Q

When would you use TaskExecutor instead of simply creating your own ExecutorService?

intermediate

Tests whether you know Spring's TaskExecutor abstraction lets you swap thread-pool implementations via configuration and integrates with Spring's lifecycle/context propagation, which a manually created ExecutorService doesn't get for free.

Q

Why can an unbounded executor queue hide an overload problem until the application crashes?

advanced

Tests whether you know an unbounded queue never triggers rejection or backpressure -- tasks just keep piling up in memory, so the system looks fine until the queue itself exhausts the heap, far later than when it actually became overloaded.

Q

Why can a Java application be slow even when CPU usage is low?

advanced

Tests whether you suspect threads blocked waiting -- on I/O, lock contention, GC pauses, or a slow downstream dependency -- since low CPU with high latency almost always points to waiting, not computing, and a thread dump confirms where.

Q

How would you size thread pools for CPU-bound versus I/O-bound workloads?

intermediate

Tests whether you know CPU-bound pools should be sized near the core count (more threads just add context-switch overhead), while I/O-bound pools can be sized much larger since threads spend most of their time blocked, not competing for CPU.

Q

Double-checked locking singleton without volatile: what can a second thread see?

advanced

Tests whether you know a second thread can see a partially-constructed object -- without volatile, the JIT/JVM can reorder the reference assignment ahead of the constructor finishing, so the null-check passes but the fields aren't initialized yet.

Q

ThreadLocal inside a thread pool: where is the leak, and what one line stops it?

advanced

Tests whether you know pooled threads are reused across tasks, so a ThreadLocal set by one task silently leaks into the next task on that same thread unless you call threadLocal.remove() in a finally block when the task finishes.

Q

Two threads increment a shared long with no synchronized and no atomic. Give two different reasons the result is wrong.

advanced

Tests whether you name both the read-modify-write race (lost updates from interleaved increments) and the separate non-atomicity of a 64-bit long/double read-write on a 32-bit JVM, which can produce a torn value made of two different writes' halves.

Q

Why volatile doesn't make count++ atomic

intermediate

Tests whether you know count++ is actually read-modify-write (three separate steps), and volatile only makes each individual read or write visible across threads -- it does nothing to stop two threads interleaving between those steps.

Q

What happens if a thread acquires a ReentrantLock and never calls unlock()? Why should unlock() sit in a finally block?

intermediate

Tests whether you know an un-released ReentrantLock permanently starves every other thread waiting on it, since unlike synchronized blocks, it is never auto-released on exception -- so unlock() must be in finally to guarantee release regardless of how the critical section exits.

Q

Difference between lock(), tryLock() and lockInterruptibly().

intermediate

Tests whether you know lock() blocks indefinitely and ignores interrupts, tryLock() returns immediately (or after a timeout) with a boolean instead of blocking, and lockInterruptibly() blocks but responds to thread interruption -- each suited to a different deadlock-avoidance strategy.

Q

Can ReentrantLock be fair? What is the performance trade-off?

intermediate

Tests whether you know new ReentrantLock(true) enforces strict FIFO ordering to prevent thread starvation, at the cost of throughput -- fair locks have higher overhead and lower overall throughput than the default barging (unfair) mode under contention.

Q

Read-write lock starvation: why can a writer starve under continuous readers?

advanced

Tests whether you know ReentrantReadWriteLock's default non-fair mode lets new readers keep acquiring the shared lock as long as any reader holds it, so a steady stream of incoming readers can indefinitely delay a writer waiting for exclusive access.

Q

What happens when a synchronized method calls another synchronized method on the same object?

intermediate

Tests whether you know Java monitor locks are reentrant -- the same thread already holding the lock on that object can re-acquire it without deadlocking itself, with an internal hold count tracking nested acquisitions.

Q

False Sharing & Concurrent Programming

advanced

Tests whether you know independent variables written by different threads can still cause cache-line ping-ponging if they happen to share a CPU cache line, and that padding or @Contended is the fix even though there's no actual data race.

Q

Why is holding a lock while making a network call dangerous?

advanced

Tests whether you know a slow or hung network call turns a short critical section into an unbounded one, blocking every other thread waiting on that lock for as long as the network call takes -- effectively letting an external dependency's latency become your application's lock contention.

Q

How can a timeout on a lock stop one failure from blocking the whole application?

advanced

Tests whether you reach for tryLock(timeout) to fail fast and free the thread instead of waiting forever, bounding the blast radius of one stuck operation so it can't starve the rest of the application's threads.

Q

Visibility & volatile — CPU caches, stale reads, and how volatile flush/invalidate works

advanced

Tests whether you understand volatile forces a write to flush from the writing CPU's cache (store barrier) and forces a read to invalidate and re-fetch from main memory (load barrier), rather than just treating it as a vague 'makes it thread-safe' keyword.

Q

What is lock escalation? Can excessive locking become a scalability bottleneck?

intermediate

Tests whether you know lock escalation (common in DBs, but conceptually similar in-app) is the shift from fine-grained to coarser-grained locking to reduce overhead, and that over-applying it serializes work that could otherwise run concurrently, directly capping throughput.

Q

AtomicInteger & CAS — the compare-and-swap loop, lock-free counters, when to reach for LongAdder

advanced

Tests whether you can explain the CAS retry loop (read, compute, compare-and-swap, retry on failure) and know LongAdder outperforms AtomicInteger under heavy contention by striping the counter across cells and summing them only on read.

Q

How can nested locks across classes or services cause an unexpected deadlock?

advanced

Tests whether you know deadlock risk isn't limited to one obvious method -- if class A locks X then Y while class B locks Y then X, in completely different call paths, you get a circular wait that only shows up under specific timing, invisible from reading either class alone.

Q

How can a non-thread-safe collection be used with Stream API?

advanced

Tests whether you know a sequential stream over a non-thread-safe collection is safe as long as the source isn't mutated during the stream, but a parallelStream() on the same collection needs a concurrent or externally synchronized source, or you'll get ConcurrentModificationException or corrupted results.

Q

How would you prevent race conditions in a payment workflow?

advanced

Tests whether you reach for DB-level guarantees (unique constraints, optimistic locking with a version column, idempotency keys) rather than in-JVM synchronization, since payment correctness must hold across multiple instances, not just one process.

Q

What are the different types of thread pools in Java?

intermediate

Tests whether you know the trade-offs behind each Executors factory method -- fixed (bounded, steady load), cached (unbounded, bursty short tasks), single-threaded (serialized execution), and scheduled (delayed/periodic tasks) -- rather than treating them as interchangeable.

Q

Will synchronized in a Spring Boot service prevent duplicate orders across 3 instances? Can synchronized protect data stored in a database?

advanced

Tests whether you know synchronized only coordinates threads within a single JVM -- it has zero effect across 3 separate instances, each with its own lock, and it never protects database state since a second process can mutate the same row through a completely different lock.

Q

Why does a distributed application need a different locking approach than a single JVM? What is a distributed lock and when do you actually need one?

intermediate

Tests whether you know in-JVM locks only coordinate threads sharing the same memory, so multiple instances need an external coordination point (Redis, ZooKeeper, DB row lock) -- and that you should reach for one only when true cross-instance mutual exclusion is required, not as a default.

Q

Why is Redis-based distributed locking tricky? What happens if a JVM crashes while holding a distributed lock?

advanced

Tests whether you know the lock needs a TTL so a crashed holder's lock expires instead of deadlocking everyone forever, and whether you're aware of the clock-drift/failover edge cases (the motivation behind algorithms like Redlock) that make naive SETNX locking unsafe at scale.

Q

Duplicate orders appear under high traffic though the code shows no obvious race. How do you investigate synchronization, DB constraints, isolation levels, idempotency and distributed concurrency?

advanced

Tests whether you systematically check layer by layer -- in-JVM synchronization (useless across instances), DB isolation level (read uncommitted/committed allows double-reads), missing unique constraints, and absent idempotency keys -- instead of assuming the bug is a classic in-memory race.

Q

What is a BlockingQueue and where do you use it in real applications?

intermediate

Tests whether you know BlockingQueue handles producer-consumer coordination internally (put() blocks when full, take() blocks when empty) so you don't hand-roll wait/notify, and can name a real use like a bounded work queue feeding a thread pool.

Q

What is ThreadLocal and where is it used?

intermediate

Tests whether you know ThreadLocal gives each thread its own isolated copy of a variable (common for per-request context like a DB connection or user session in a servlet thread), distinct from a shared field that would need synchronization.

Q

Why does volatile guarantee visibility but not atomicity?

intermediate

volatile ensures every thread reads the latest written value (no stale caching) but does nothing to make a compound operation like count++ (read-modify-write) atomic — two threads can still both read the same value before either writes back, losing an update.

Q

How does ConcurrentHashMap achieve thread safety without locking the entire map?

advanced

It partitions the map internally (historically into segments, now into per-bin locks in Java 8+) so different threads can operate on different parts of the map concurrently — only the specific bin being modified is locked, not the whole structure.

Q

Heap Dump vs Thread Dump?

intermediate

Tests whether you know a heap dump is a snapshot of live objects for diagnosing memory issues, while a thread dump is a snapshot of every thread's stack and state (RUNNABLE/BLOCKED/WAITING) for diagnosing deadlocks, contention, or hangs -- and that they're captured and analyzed differently.

Q

When would you choose LongAdder over AtomicInteger?

advanced

Under high contention with many threads incrementing the same counter, AtomicInteger's single compare-and-swap variable becomes a bottleneck. LongAdder internally spreads updates across multiple cells and sums them only when you read the total, trading a slightly more expensive read for much cheaper concurrent writes.

Q

How do you size a ThreadPoolExecutor differently for CPU-bound vs I/O-bound workloads?

intermediate

CPU-bound: pool size ≈ number of CPU cores (more threads than cores just adds context-switching overhead). I/O-bound: pool size can be much larger than core count, since threads spend most of their time blocked waiting on I/O rather than actually using the CPU.

Q

Does CompletableFuture create its own thread pool? Which pool does it use by default?

advanced

Tests whether you know CompletableFuture's async methods without an explicit Executor fall back to ForkJoinPool.commonPool() by default, which is shared process-wide and easily starved by blocking work -- a key reason to always pass a dedicated Executor in production code.

Q

What's the difference between thenApply(), thenCompose(), and thenCombine() in CompletableFuture?

advanced

thenApply() transforms the result with a plain function. thenCompose() chains to ANOTHER CompletableFuture-returning function (flattens nested futures, like flatMap). thenCombine() waits for two independent futures and combines both results together.

Q

You receive a production thread dump with hundreds of BLOCKED threads — how do you identify the root cause?

advanced

Look for the small number of threads actually holding the contested lock (state RUNNABLE or waiting on I/O) versus the many threads BLOCKED waiting for it — that lock holder, and what it's doing (a slow query, an external call), is almost always the actual bottleneck, not the blocked threads themselves.

Java 8 & Streams

Q

Predicate, Function, Consumer, Supplier — explain and differentiate

intermediate

Tests whether you can place each by its signature shape -- Predicate<T> takes a value and returns boolean, Function<T,R> takes a value and returns a different type, Consumer<T> takes a value and returns nothing, Supplier<T> takes nothing and returns a value -- the four shapes that cover almost every functional-interface use case in the JDK.

Q

What are the key features introduced in Java 8?

intermediate

Tests whether you can name the features that actually changed how Java code is written -- lambdas, the Stream API, default/static interface methods, Optional, and the new java.time package -- rather than a vague 'it added functional programming'.

Q

Given an Employee list, group employees by department and find the employee with the highest salary in each department

intermediate

Tests whether you reach for Collectors.groupingBy(Employee::getDepartment, Collectors.maxBy(Comparator.comparing(Employee::getSalary))) -- a downstream collector nested inside groupingBy -- rather than grouping first and then iterating each group manually to find the max.

Q

Difference between map() and flatMap().

intermediate

Tests whether you know map() transforms each element 1:1 (possibly producing a stream of streams), while flatMap() transforms and then flattens nested structures into a single stream -- the mechanism you need whenever each input maps to zero or more outputs.

Q

What are intermediate and terminal operations in the Stream API?

intermediate

Tests whether you understand intermediate operations (filter, map) are lazy and just build a pipeline description, while a terminal operation (collect, forEach) is what actually triggers execution -- nothing runs until a terminal op is called.

Q

Find the second-highest salary in each department using Java Streams

intermediate

Tests whether you can nest a per-group sort/distinct/skip pipeline inside groupingBy's downstream collector to get the second value within each group, rather than only knowing how to find the second-highest across a flat list.

Q

Functional interface vs marker interface.

intermediate

Tests whether you know a functional interface has exactly one abstract method (a lambda target, e.g. Runnable), while a marker interface has no methods at all and exists purely to tag a class for reflective or runtime checks (e.g. Serializable).

Q

What happens when we try to reuse a stream?

intermediate

Tests whether you know a Java Stream is single-use -- once a terminal operation consumes it, calling another operation on the same stream throws IllegalStateException, because streams model a one-time traversal, not a reusable collection.

Q

What are some benefits of using Streams?

intermediate

Tests whether you go beyond 'cleaner code' to name declarative pipeline composition, built-in laziness that avoids unnecessary work, and easy parallelization via parallelStream() without manually managing threads.

Q

What are Records in Java? Do Records have equals() and hashCode()?

intermediate

Tests whether you know records are compiler-generated immutable data carriers that automatically get equals(), hashCode(), and toString() derived from their components -- so two records with identical component values are equal, unlike a plain class where you'd have to write that logic yourself.

Q

Explain Java 8 Streams and Lambda expressions.

intermediate

Tests whether you can explain lambdas as syntactic sugar for implementing a functional interface inline, and Streams as the API built on top of lambdas to express data processing as a declarative pipeline instead of imperative loops.

Q

What is a Stream, and how is it different from a Collection?

intermediate

Tests whether you know a Collection is an in-memory data structure you store elements in, while a Stream is a view over a data source that computes elements on demand and doesn't store anything itself -- it describes a computation, not storage.

Q

What is lazy evaluation in Java Streams?

intermediate

Tests whether you know intermediate operations only build up a pipeline of transformations without executing, and the entire chain runs element-by-element only when a terminal operation pulls a result -- which is why short-circuiting ops like findFirst() can skip most of the data entirely.

Q

Difference between filter(), map() and reduce().

intermediate

Tests whether you can place each in the pipeline correctly: filter() selects elements by a predicate, map() transforms each element's value, and reduce() is the terminal fold that combines all elements into a single accumulated result.

Q

Given a list of Strings, how would you filter strings with length greater than 3, sort them based on length, and return the top 3 strings?

intermediate

Tests whether you can chain filter().sorted(Comparator.comparingInt(String::length)).limit(3) correctly in one readable pipeline, understanding that limit() after sorted() is what actually bounds the result to the top N.

Q

Difference between findFirst() and findAny().

intermediate

Tests whether you know findFirst() guarantees the encounter-order element even in a parallel stream (at the cost of synchronization), while findAny() makes no ordering guarantee and can return as soon as any thread finds a match, making it faster in parallel.

Q

How does distinct() work in a Stream?

intermediate

Tests whether you know distinct() relies on equals()/hashCode() to filter duplicates (using a HashSet-like mechanism internally), so it only works correctly if those methods are implemented consistently on the element type.

Q

How do you sort objects using Java Streams?

intermediate

Tests whether you reach for sorted(Comparator.comparing(...)) and chain .thenComparing() for multi-field sorts, rather than writing a manual Comparator class for something the Stream API already composes declaratively.

Q

How do you group and partition data using Collectors.groupingBy() and partitioningBy()?

intermediate

Tests whether you know groupingBy() produces an arbitrary-keyed Map (often with a downstream collector for counting/aggregating per group), while partitioningBy() is the special case that always produces exactly two buckets keyed by a boolean predicate.

Q

Stream.toList() vs Collectors.toList().

intermediate

Tests whether you know Stream.toList() (Java 16+) returns an unmodifiable list with less boilerplate, while Collectors.toList() makes no guarantee about mutability or the exact List implementation -- a subtle API contract difference, not just a shorthand.

Q

Sequential stream vs parallel stream: how do they differ?

intermediate

Tests whether you know parallelStream() splits work across ForkJoinPool.commonPool() threads using the Spliterator abstraction, and that this only pays off for large datasets with CPU-bound, stateless, non-ordered work -- not for small collections or I/O-bound tasks.

Q

How would you find duplicate records in a table without using GROUP BY?

intermediate

Tests whether you reach for a self-join on the matching columns with a row-identity inequality (or a window function like ROW_NUMBER() OVER (PARTITION BY ...)) to flag duplicates, showing you know more than one way to express 'duplicate' in SQL beyond the obvious GROUP BY + HAVING COUNT(*) > 1.

Q

When should you avoid using parallelStream()?

intermediate

Tests whether you know to avoid it for small collections (splitting/merging overhead exceeds the gain), I/O-bound work (it shares the same commonPool as other parallel streams app-wide, so one blocking call starves everyone), and operations needing strict ordering or mutable shared state.

Q

Using Streams, find duplicate elements, the frequency of each element, and the second-highest value (for example, second-highest salary).

intermediate

Tests whether you reach for Collectors.groupingBy(Function.identity(), Collectors.counting()) for frequency/duplicates, and sorted().distinct().skip(n-1).findFirst() (or a bounded approach) for the nth-highest, rather than sorting the whole dataset unnecessarily.

Q

A Stream-based operation is slow in production. How would you identify and optimize the bottleneck?

advanced

Tests whether you profile before guessing -- checking for accidental boxing/unboxing, unnecessary intermediate collection materialization, misuse of parallelStream() on I/O-bound work, and whether a plain loop would actually be faster for the data size involved.

Q

Sort a map by value

intermediate

Tests whether you reach for entrySet().stream().sorted(Map.Entry.comparingByValue()) and collect into a LinkedHashMap to preserve the sorted order, since a Map itself has no inherent sort-by-value operation and a regular HashMap wouldn't retain any ordering you impose on it.

Q

How would you identify legacy classes suitable for conversion to Java 17 records?

advanced

Tests whether you look for the specific shape records demand -- immutable data carriers with only a constructor, getters, and generated equals/hashCode/toString, and no additional mutable state or inheritance from another class -- since classes with business logic, mutability, or an existing class hierarchy aren't good candidates.

Q

Benefits and challenges of records in business models?

advanced

Tests whether you weigh the real trade-off -- records cut boilerplate and guarantee immutability for DTOs/value objects, but their immutability and inability to extend another class make them a poor fit for entities with mutable state, JPA proxying needs, or evolving inheritance hierarchies.

Q

Java 7 vs Java 8+ ConcurrentHashMap?

advanced

Tests whether you know Java 7's ConcurrentHashMap used segment-level locking (a fixed array of locks, each guarding a slice of the table), while Java 8 moved to per-bucket synchronization combined with CAS operations on individual bins -- finer-grained locking that improves concurrency, plus the same bucket-treeification HashMap gained.

Q

What is the latest LTS Java version? Key features and differences between Java 17 and Java 21 (Virtual Threads, Sequenced Collections, Pattern Matching)

intermediate

Tests whether you can name what actually changed between the two LTS releases -- virtual threads (Project Loom) for cheap massive concurrency, sequenced collections giving a consistent first()/last() API across ordered types, and expanded pattern matching for switch -- rather than treating 17 and 21 as interchangeable 'modern Java.'

Q

How does Stream API work internally?

advanced

Tests whether you know a stream pipeline is built from a source Spliterator plus a chain of stateless operation wrappers, and that it only actually iterates once a terminal operation pulls elements through the whole chain one at a time -- it's not a series of independent passes over intermediate collections.

Q

Using Java Streams, process transaction data and find the Top 3 clients by transaction amount

intermediate

Tests whether you chain groupingBy (to aggregate per client) with a downstream summing collector, then sort the resulting map's entries by value and limit(3) -- a two-stage pipeline (aggregate, then rank) rather than trying to do both in a single pass.

Q

Is a given interface with equals(), toString(), and a default method still a valid @FunctionalInterface? Explain why.

advanced

Tests whether you know the single-abstract-method rule only counts methods that aren't already implementations of java.lang.Object's public methods -- redeclaring equals()/toString() as abstract doesn't add a second SAM, and default methods never count as abstract, so the interface is still a valid functional interface.

Q

Given a list of account transactions such as A:+100, B:+200, A:-50, C:+300, B:-100, A:+150, calculate the final balance for each account — explain approach, write code, time/space complexity, and solve using Java 8 features like Map.merge()

advanced

Tests whether you reach for Map.merge(account, amount, Integer::sum) to fold transactions into running balances in a single O(n) pass, rather than grouping transactions first and summing each group separately in a second pass.

File I/O & NIO

Collections Framework

Q

What is the difference between List and Set in Java?

beginner

A List is an ordered collection that allows duplicate elements and lets you access items by index (get(i)); a Set is an unordered collection (except LinkedHashSet/TreeSet) that does not allow duplicates, enforced via equals()/hashCode(). Choose List when order and duplicates matter, Set when uniqueness is the requirement.

Q

What is the difference between HashSet, LinkedHashSet, and TreeSet?

beginner

HashSet offers O(1) average add/contains but no ordering guarantee; LinkedHashSet preserves insertion order at a small extra memory cost (a backing linked list); TreeSet keeps elements sorted (natural order or a Comparator) at O(log n) per operation, backed by a red-black tree. Pick based on whether you need speed, insertion order, or sorted order.

Q

What is the difference between CopyOnWriteArraySet and a regular HashSet?

intermediate

CopyOnWriteArraySet is a thread-safe Set backed by a CopyOnWriteArrayList — every mutation copies the entire underlying array, so reads never block and never throw ConcurrentModificationException, but writes are expensive and it scales poorly for write-heavy or large collections. A plain HashSet is not thread-safe at all and needs external synchronization (or Collections.synchronizedSet) for concurrent access.

Q

What is the difference between Comparable and Comparator in Java?

beginner

Comparable is implemented by the class itself via compareTo(), defining one single 'natural' ordering (e.g., a Product sorting by its own ID); Comparator is a separate object implementing compare(a, b), letting you define multiple, external, interchangeable orderings for the same class (e.g., sort Products by price, then by name) without modifying the class itself.

Q

What is the difference between Collection and Collections in Java?

beginner

Collection (singular) is the root interface of the collections hierarchy — List, Set, and Queue all extend it, and it defines the core contract (add, remove, size, iterator). Collections (plural) is a utility class full of static helper methods that operate ON collections — sort(), reverse(), unmodifiableList(), synchronizedList(), and so on.

Q

What is the difference between the Collections Framework and the Streams API?

beginner

The Collections Framework is about storing and organizing data in memory (List, Set, Map and their implementations); the Streams API is about processing that data declaratively — filtering, transforming, and aggregating a sequence of elements without manually writing loops. A Stream isn't a data structure at all; it's a pipeline computed lazily over a source, most commonly a Collection.

Q

Explain the Collections hierarchy — List, Set, Map, Queue.

beginner

Tests whether you have a clear mental map of Java's core collection interfaces and how they relate to each other.

Q

How does HashMap work internally? (hashing, buckets, collision)

intermediate

One of the most-asked Java questions — tests whether you actually understand hashing, bucket placement, and collision resolution, not just usage.

Q

What is the difference between HashMap and Hashtable?

intermediate

Tests whether you know the thread-safety, null-key, and performance differences between these two legacy-adjacent classes.

Q

A HashMap has millions of entries and suddenly becomes slow. How would you investigate?

advanced

Tests whether you know to check hashCode() quality, load factor, and whether entries are treeifying due to collisions.

Q

How does ConcurrentHashMap differ from HashMap?

intermediate

Tests whether you understand segment/bucket-level locking and why it beats simply synchronizing a whole HashMap.

Q

You insert a mutable object as a HashMap key and later modify it. What can go wrong?

advanced

Tests whether you know a changed hashCode() after insertion makes the entry effectively unfindable at its original bucket.

Q

What is fail-fast vs fail-safe iterator?

intermediate

Tests whether you know why ConcurrentModificationException happens and which collections avoid it, and how.

Q

Implement an LRU cache using LinkedHashMap.

advanced

A very common coding-round question testing whether you know LinkedHashMap's access-order mode and removeEldestEntry hook.

Q

Your CopyOnWriteArrayList is creating high memory usage and GC pressure. Why?

advanced

Tests whether you know every single write copies the entire underlying array, which is brutal for write-heavy or large lists.

Q

What happens when HashMap capacity exceeds load factor? Explain rehashing.

advanced

Tests whether you understand the resize trigger, the doubling behavior, and why rehashing is expensive.

Q

A ConcurrentModificationException occurs in a single-threaded application. How is that possible?

advanced

Tests whether you know this exception is about structural modification during iteration, not literally about concurrent threads.

Q

You're reviewing production code using Collections.synchronizedMap(). Would you keep it or replace it? What factors decide?

advanced

Tests whether you can weigh whole-map locking against ConcurrentHashMap's finer-grained concurrency for the actual access pattern.

Q

Why can a poor hashCode() implementation destroy HashMap performance?

advanced

Tests whether you know a constant or low-quality hashCode collapses lookups from O(1) toward O(n) by funneling everything into one bucket.

Q

Two threads call computeIfAbsent() for the same key on a ConcurrentHashMap at the same time. What behavior do you expect?

advanced

Tests whether you know ConcurrentHashMap guarantees the mapping function runs atomically per key, avoiding duplicate computation.

Q

What is EnumMap and why is it more performant than HashMap for enum keys?

intermediate

Tests whether you know EnumMap uses ordinal-based array indexing instead of general-purpose hashing.

Q

You need the top 10 most frequent items out of millions of events. Which collections would you combine to solve this efficiently?

advanced

Tests whether you know to pair a frequency HashMap with a bounded PriorityQueue instead of sorting everything.

Q

A cache should automatically release entries when their keys are no longer strongly referenced elsewhere. What would you use?

advanced

Tests whether you know WeakHashMap lets the garbage collector reclaim entries whose keys have become otherwise unreachable.

Q

When should you choose ArrayList over LinkedList (and vice versa)?

intermediate

Almost always ArrayList — get(index) is O(1) vs O(n) for LinkedList, and contiguous memory gives far better CPU cache locality (a real benchmark: getting a middle element from 10 million items takes ~1ms on ArrayList vs ~125ms on LinkedList). LinkedList only wins for frequent inserts/removals at the head.

Q

What are the two mandatory rules for overriding hashCode(), and what breaks if you only override equals()?

intermediate

Equal objects (per equals()) must have equal hash codes, and a hash code must stay consistent within one JVM run. If you override equals() without hashCode(), logically equal objects can land in different HashMap buckets, making get() fail to find entries that should match.

Q

When would you use TreeMap or LinkedHashMap over a plain HashMap?

beginner

TreeMap when you need keys in sorted order (O(log n), definitely slower than HashMap); LinkedHashMap when you need to preserve insertion order while keeping HashMap's O(1) average lookup, just with a small extra pointer-overhead per entry.

Concurrency Machine Coding

Q

Find the highest number in a random matrix using threads

advanced

Tests whether you can parallelize a reduction correctly -- splitting rows across threads, computing partial maxima independently, then combining results without a shared mutable variable causing races.

Q

Implement a thread-safe task scheduler

advanced

Tests whether you pick the right concurrent structure for scheduling (a DelayQueue or PriorityBlockingQueue plus a worker thread) and avoid busy-waiting by blocking on the next task's due time.

Q

Design a distributed rate limiter — first defend which algorithm, then design it

advanced

Tests whether you can justify an algorithm choice (token bucket vs sliding window log vs sliding window counter) on accuracy-vs-memory trade-offs, then design the shared-state coordination (Redis + Lua script for atomicity) across nodes.

Q

Implement a bounded queue. Then build a thread pool on top of it — no ExecutorService allowed

advanced

Tests whether you can implement producer/consumer blocking correctly with wait()/notifyAll() (or a Condition) on a fixed-capacity buffer, then wire worker threads to pull from it without using any java.util.concurrent executor.

Q

A playground supports one team at a time, with ten players maximum — assign players without starvation

advanced

Tests whether you recognize this as a bounded-resource admission problem needing fairness (e.g., a semaphore plus a FIFO wait queue) so that a steady stream of new arrivals can't indefinitely starve players already waiting.

Q

Concurrent searchers, inserters and deleters on a linked list — searches concurrent, one insert at a time, deletion blocks all

advanced

Tests whether you can design tiered locking (a ReadWriteLock-like scheme) where searches share a read lock, inserts take an exclusive insert lock, and deletes escalate to block every other operation -- matching each operation's actual conflict requirements.

Q

Implement file read/write using offsets, then make it multithreaded

advanced

Tests whether you know RandomAccessFile (or FileChannel.read/write with an explicit position) lets multiple threads operate on disjoint byte ranges of the same file concurrently without a shared file pointer causing interference.

Q

Machine coding: in-memory Twitter — createUser, postTweet, getNewsFeed, follow, unfollow

advanced

Tests whether you can design clean object boundaries (User, Tweet, a follow graph) and implement getNewsFeed as a k-way merge of each followee's tweets by timestamp, rather than sorting the full combined list each call.

Q

Machine coding: train and platform scheduler — working implementation in 60-75 minutes

advanced

Tests whether you can model trains and platforms as an interval-scheduling/allocation problem and produce a complete, compiling solution under real time pressure rather than a half-finished sketch.

Q

Machine coding: in-memory pull-based queue with multiple publishers and consumers

advanced

Tests whether you can design a pull model (consumers poll/claim messages) with correct offset or claim tracking per consumer, avoiding the same message being delivered twice under concurrent pulls.

Q

Machine coding: implement mkdir, pwd and cd (cd supports wildcards)

advanced

Tests whether you model the filesystem as an in-memory tree of directory nodes with parent pointers (for cd .. and pwd), and implement wildcard matching for cd as pattern matching over sibling directory names.

Q

Write a program where thread 1 computes (a+b), thread 2 computes (c+d), and the main thread multiplies the two results

intermediate

Tests whether you know the main thread must join() both worker threads (or get() both Futures) before reading their results, since reading shared variables without that happens-before edge risks seeing stale or partial values.

Q

Online gaming platform exercise: model Player, MatchResult, GameManager with WIN/LOSS/DRAW outcomes, record results from the player's perspective, and fix a bug in GameManager so provided tests pass

advanced

Tests whether you can design the Player/MatchResult relationship so a single MatchResult correctly reports WIN for one player and LOSS for the other from each player's perspective, and can root-cause a failing test against that symmetry rather than just patching the assertion.

String & StringBuilder

OOP & Core Syntax

Q

What are the access modifiers in Java, and what does each one control?

beginner

private restricts access to within the same class; default (no modifier) allows access within the same package; protected allows access within the package plus subclasses in other packages; public allows access from anywhere. Choosing the narrowest modifier that still works is the standard encapsulation practice.

Q

What is the difference between this and super keywords in Java?

beginner

this refers to the current object instance — used to disambiguate a field from a same-named constructor parameter, or to call another constructor in the same class (this(...)). super refers to the immediate parent class — used to call the parent's constructor (super(...)) or to access a parent's overridden method/field explicitly.

Q

Can a constructor be declared final or static in Java?

beginner

No — final prevents a method from being overridden, but constructors are never inherited or overridden in the first place, so final on a constructor is meaningless and won't compile. static implies belonging to the class rather than an instance, but a constructor's entire job is to initialize a specific instance, so static is equally disallowed.

Q

Can you override a private or static method in Java?

beginner

No. Private methods aren't inherited at all, so a same-named method in a subclass is a completely new, unrelated method, not an override. Static methods belong to the class, not an instance, so a same-named static method in a subclass hides the parent's version (resolved at compile time based on the reference type) rather than overriding it (which is resolved at runtime based on the actual object type).

Q

What is a marker interface in Java? Give an example.

beginner

A marker interface has no methods or fields at all — its only purpose is to 'tag' a class so that other code (often via instanceof or reflection) can check for that tag and change behavior accordingly. Serializable and Cloneable are classic examples — implementing them signals intent to the JVM without requiring any method implementation (annotations have largely replaced this pattern in modern Java).

Q

Can you catch multiple exception types in a single catch block?

beginner

Yes, using multi-catch syntax introduced in Java 7: catch (IOException | SQLException e) { ... } — this avoids duplicating the same handling logic across multiple catch blocks. The caveat: the exception types in a multi-catch can't be related by inheritance (you can't combine a class and its own subclass), and the resulting variable e is implicitly final.

Q

Can you throw a checked exception inside a lambda expression's body?

intermediate

Only if the functional interface's abstract method itself declares that checked exception in its throws clause — most built-in interfaces like Function or Consumer don't, so a lambda implementing them can't throw a checked exception directly and must either catch it internally, wrap it in an unchecked exception, or use a custom functional interface that declares the checked exception.

Q

Can you start the same Thread object twice in Java?

beginner

No — calling start() a second time on the same Thread instance throws IllegalThreadStateException. Once a thread has run and terminated, that Thread object is permanently done; to run the same task again you need to create a brand-new Thread instance (or, better, resubmit the task to an ExecutorService, which reuses pooled threads under the hood).

Arrays & Matrices

Multithreading Basics

Functional Programming

Q

What are Method References in Java, and what are the 4 types?

beginner

A method reference is shorthand for a lambda that just calls an existing method — written as Class::method. The 4 types are: a static method (String::valueOf), an instance method on a particular object (someList::add), an instance method on an arbitrary object of a type (String::toUpperCase, where the object becomes the first parameter), and a constructor reference (ArrayList::new).

Q

How does Collectors.groupingBy() work in the Stream API? Give an example.

intermediate

groupingBy() collects stream elements into a Map, where a classifier function you supply determines the key for each element and all elements mapping to the same key are collected into a List under that key by default. For example, employees.stream().collect(Collectors.groupingBy(Employee::getDepartment)) produces a Map<String, List<Employee>> grouping employees by department; a second argument (a downstream collector) can further reduce each group, e.g. to a count or an average.

Q

What is the Function functional interface in Java, and when do you use it?

beginner

Function<T, R> represents a function that takes one argument of type T and returns a result of type R, via its single abstract method R apply(T t). It's the go-to interface for transformation logic — e.g. Function<String, Integer> length = String::length — and is what Stream.map() expects as its argument.

Q

What is the Predicate functional interface in Java, and when do you use it?

beginner

Predicate<T> represents a boolean-valued test on a single argument, via its abstract method boolean test(T t). It's the interface Stream.filter() and List.removeIf() expect, and it exposes default methods and(), or(), and negate() for composing multiple conditions, e.g. isAdult.and(isVerified).

Q

What is the Supplier functional interface in Java, and when do you use it?

beginner

Supplier<T> takes no arguments and returns a value of type T, via its abstract method T get(). It's used for lazy or deferred value generation — e.g. Optional.orElseGet(supplier), where the supplier is only invoked if the Optional is actually empty, avoiding unnecessary work compared to orElse(), which always evaluates its argument eagerly.

Q

What is the Consumer functional interface in Java, and when do you use it?

beginner

Consumer<T> takes one argument and returns nothing, via its abstract method void accept(T t) — it's for operations performed purely for their side effects, like printing or saving. It's the interface Stream.forEach() and List.forEach() expect, and its andThen() default method lets you chain multiple consumers to run in sequence on the same input.

Q

What are the BiFunction, BiPredicate, and BiConsumer functional interfaces?

beginner

They are the two-argument counterparts of Function, Predicate, and Consumer: BiFunction<T, U, R> takes two arguments and returns a result, BiPredicate<T, U> takes two arguments and returns a boolean, and BiConsumer<T, U> takes two arguments and returns nothing. A common use is Map.forEach(BiConsumer<K, V>), which receives both the key and value of each entry.

Q

What are UnaryOperator and BinaryOperator, and how do they differ from Function and BiFunction?

intermediate

UnaryOperator<T> is a specialization of Function<T, T> where the input and output types are the same — used for operations like String::toUpperCase that transform a value into the same type. BinaryOperator<T> is a specialization of BiFunction<T, T, T> for combining two values of the same type into one, which is exactly the shape Stream.reduce() expects (e.g. Integer::sum).

Q

What are primitive functional interfaces in Java, and why do they exist?

intermediate

Primitive functional interfaces — IntPredicate, IntFunction, IntConsumer, IntSupplier, and their long/double equivalents — are specialized versions of the generic functional interfaces built specifically for int, long, and double. They exist purely for performance: using a generic Function<Integer, R> would autobox every int into an Integer object, creating unnecessary object overhead in hot loops, whereas IntFunction<R> operates directly on the primitive with no boxing.

Q

What does the Stream filter() method do, and how is it different from map()?

beginner

filter() takes a Predicate and returns a new stream containing only the elements that satisfy it — it never changes the number of elements' TYPE, only how many pass through. map() takes a Function and transforms every element into something else, keeping the same count but potentially changing the type — the two are commonly chained, e.g. filter then map to select and transform in one pipeline.

Q

What does the Stream collect() method do, and what's the difference between collect() and forEach()?

beginner

collect() is a terminal operation that gathers the stream's elements into a final result — a List, Set, Map, or a custom accumulation — using a Collector like Collectors.toList() or Collectors.joining(). forEach() is also terminal but performs a side-effecting action (like printing) per element and returns nothing; use collect() when you need a data structure back, forEach() when you just need to act on each element.

Q

What does the Stream distinct() method do, and how does it determine uniqueness?

beginner

distinct() returns a stream with duplicate elements removed, determining uniqueness via each element's equals() (and, for hashing efficiency, hashCode()) method. For custom objects, this means distinct() only works correctly if equals()/hashCode() are properly overridden — otherwise it falls back to default object-identity comparison and won't remove logically-equal-but-distinct-instance duplicates.

Q

What do the Stream limit() and skip() methods do?

beginner

limit(n) truncates the stream to at most the first n elements, useful for pagination or top-N results. skip(n) discards the first n elements and returns the rest — combining skip(offset).limit(pageSize) is a common pattern for implementing simple in-memory pagination over a stream.

Q

What does the Stream count() method do, and how does it interact with filter()?

beginner

count() is a terminal operation that returns the number of elements in the stream as a long. Chained after filter(), e.g. list.stream().filter(p).count(), it's an efficient way to count how many elements satisfy a condition — Java's Stream implementation can even skip actually materializing elements in some cases, computing the count more efficiently than a full iteration when the pipeline allows it.

Q

What is the difference between anyMatch(), allMatch(), and noneMatch() in the Stream API?

beginner

All three are short-circuiting terminal operations that take a Predicate and return a boolean: anyMatch() returns true if AT LEAST ONE element satisfies it, allMatch() returns true only if EVERY element satisfies it, and noneMatch() returns true if NO element satisfies it. Being short-circuiting means they stop processing the stream the instant the answer is determined, rather than always scanning every element.

Java 8+ Features

Exception Handling

Modern Java (11-25)

Q

Are Java Records truly immutable? What are their limitations?

intermediate

Tests whether you know records give you shallow immutability for their own fields, not deep immutability of referenced objects.

Q

What are Sealed Classes in Java 17 — how do they enforce domain modeling?

intermediate

Tests whether you know sealed types let you declare an exhaustive, closed set of permitted subtypes at compile time.

Q

What is Pattern Matching for switch (Java 21) and how does it improve type-safe branching?

intermediate

Tests whether you know how it eliminates the manual instanceof-and-cast boilerplate switch statements used to require.

Q

What are Sequenced Collections in Java 21?

intermediate

Tests whether you know this new interface finally gives a consistent way to access first/last elements across ordered collection types.

Q

How does Java 21's virtual thread implementation handle blocking I/O internally — what is carrier thread pinning?

advanced

Tests whether you understand the mechanism that lets thousands of virtual threads share a small pool of OS carrier threads.

Q

What is the difference between var (Java 10) and explicitly typed declarations — when does var hurt readability?

intermediate

Tests whether you know var is fine when the type is obvious from context, but can obscure intent when it isn't.

Q

Java 25 Compact Object Headers (JEP 519) — what does it mean for production workloads?

advanced

Tests whether you're current on recent JVM changes and know what shrinking object headers actually saves in practice.

DSA — Problem-Solving Patterns

Q

What is the Sliding Window pattern in DSA, and what class of problems does it solve efficiently?

intermediate

Tests whether you can recognize when a shrinking/growing window beats a brute-force nested loop.

Q

What is the two-pointer pattern? Give an example problem where it turns an O(n²) solution into O(n).

intermediate

Tests whether you know how converging pointers from both ends of a sorted structure eliminate redundant comparisons.

Q

What is the fast & slow pointers pattern? How does it detect a cycle in a linked list?

intermediate

Tests whether you know Floyd's algorithm and why two pointers moving at different speeds must eventually meet in a cycle.

Q

What is the merge intervals pattern? Walk through merging a list of overlapping intervals.

intermediate

Tests whether you know to sort by start time first, then merge in a single linear pass.

Q

What is the Top K Elements pattern using a heap, and why is it more efficient than sorting the entire dataset?

advanced

Tests whether you know a bounded heap gets you the top K in O(n log k) instead of paying for a full O(n log n) sort.

Q

What is the 0/1 Knapsack dynamic programming pattern, and what other problems share its structure?

advanced

Tests whether you can recognize the include-or-exclude decision structure that generalizes to many DP problems.

Q

What is the topological sort graph pattern? How does it apply to a course-scheduling / build-order problem?

advanced

Tests whether you know how to order nodes in a DAG so every dependency is processed before what depends on it.

Q

Find the Kth largest element in a stream of numbers, where new numbers keep arriving.

advanced

Tests whether you know to maintain a fixed-size min-heap instead of re-sorting on every new element.

Q

Implement an LFU (Least Frequently Used) Cache with O(1) get and put.

advanced

Tests whether you can design a harder variant of LRU that also tracks access frequency, not just recency.

Q

Find the median from a data stream — numbers keep arriving one at a time, and you must return the median at any point.

advanced

Tests whether you know the two-heap technique (a max-heap and a min-heap balanced against each other) for this classic problem.

Q

Solve the Word Ladder problem — find the shortest transformation sequence from one word to another, changing one letter at a time.

advanced

Tests whether you know to model this as a graph shortest-path problem and solve it with BFS.

JVM & GC

Q

How would you handle a 2 GB file upload without loading the entire file into JVM heap?

advanced

Tests whether you stream the upload in fixed-size chunks (via InputStream/NIO channels straight to disk or object storage) instead of buffering the whole file into a byte array, which would blow the heap regardless of its size.

Q

Object Header, Mark Word & Class Pointer

advanced

Tests whether you know every Java object's header carries a mark word (hash code, GC age, and lock state bits) plus a class pointer to its Klass metadata, and that this fixed overhead is why tiny objects are surprisingly expensive in bulk.

Q

TLAB & Object Allocation

advanced

Tests whether you know each thread gets a Thread-Local Allocation Buffer carved out of Eden so most object allocation is a lock-free bump-the-pointer operation, avoiding contention on the shared heap for the common case.

Q

Young vs Old Generation

intermediate

Tests whether you know the generational hypothesis (most objects die young) drives this split -- Young Gen is collected frequently and cheaply with a copying collector, while Old Gen holds long-lived survivors and is collected less often but more expensively.

Q

Escape Analysis & Scalar Replacement

advanced

Tests whether you know the JIT can prove an object never escapes its allocating method/thread and then replace it with its individual fields as scalars -- eliminating the heap allocation entirely rather than just optimizing around it.

Q

GC Roots & Object Reachability

intermediate

Tests whether you know GC roots (local variables on the stack, static fields, active JNI references) are the starting points for reachability, and that anything unreachable from a GC root -- even in a cycle -- becomes eligible for collection.

Q

What is a memory leak in Java if Garbage Collection is automatic?

intermediate

Tests whether you know a Java 'leak' isn't about forgetting to free memory -- it's an object staying reachable from a GC root (a static collection, a forgotten listener, an unclosed resource) long after it's logically done, so GC correctly refuses to collect it.

Q

How can unbounded caches cause memory problems?

intermediate

Tests whether you know a cache with no eviction policy or size bound is functionally a memory leak -- every entry stays reachable forever -- and that the fix is a bounded cache with an eviction strategy (LRU, TTL, or a weak-reference-based cache).

Q

How can listeners and callbacks cause memory leaks?

intermediate

Tests whether you know a long-lived publisher holding a strong reference to a listener keeps the listener's owning object (and everything it references) alive even after that object should be discarded, unless the listener is explicitly unregistered or held weakly.

Q

What is the difference between a memory leak and high memory usage?

intermediate

Tests whether you know high memory usage can be legitimate (large but bounded working set) while a leak is memory that keeps growing over time without bound -- distinguishing them requires watching the trend across GC cycles, not a single snapshot.

Q

OutOfMemoryError vs StackOverflowError?

intermediate

Tests whether you know OutOfMemoryError means the heap (or metaspace) is exhausted by live objects, while StackOverflowError means a single thread's call stack exceeded its fixed size -- almost always from unbounded or runaway recursion.

Q

How do you analyze a Heap Dump?

advanced

Tests whether you know to start from the biggest objects by retained size, walk their dominator tree to find what's holding them alive, and trace that chain back to a GC root rather than just eyeballing the largest individual object.

Q

What is a Dominator Tree?

advanced

Tests whether you know a dominator tree restructures the object graph so each object's parent is the single object that, if removed, would make it unreachable -- which is what lets a heap analyzer attribute retained memory to one true owner instead of double-counting shared references.

Q

What is a Retained Heap?

intermediate

Tests whether you know retained size is the memory that would actually be freed if an object were garbage collected (itself plus everything only it keeps alive), which is why it's the number to sort by, not shallow size.

Testing

Q

What is code coverage and line coverage?

intermediate

Tests whether you know line coverage (which lines executed) is only one coverage metric, and can push back on using it alone as a quality signal since it says nothing about branch or condition coverage within those lines.

Q

How do you improve code coverage when build fails?

intermediate

Tests whether you'd identify the specific untested branches the coverage gate is flagging and write targeted tests for them, rather than padding coverage with low-value tests just to clear the threshold.

Q

How do you verify a method is called twice in Mockito?

intermediate

Tests whether you know verify(mock, times(2)).method(...) is the right API, and that plain verify() without times() only asserts exactly one invocation.

Q

In which situations do you use PowerMock?

intermediate

Tests whether you know PowerMock exists specifically to mock what standard Mockito can't -- static methods, final classes, constructors, and private methods -- and that its need often signals code that's hard to unit test and could be refactored instead.

Q

How do you perform an effective code review?

intermediate

Tests whether you'd separate correctness/design concerns (logic bugs, missing tests, API shape) from style nits, and review for intent against the ticket rather than just scanning the diff line by line.

Q

What is integration testing? How would you write an integration test involving a DB transaction?

intermediate

Tests whether you know integration tests verify multiple components working together against real infrastructure (often a test container DB), and whether you'd wrap each test in a transaction that rolls back afterward so tests stay isolated and repeatable without manual cleanup.

Q

JUnit vs TestNG: why use TestNG and what are its benefits for automation?

intermediate

Tests whether you know TestNG's edge for automation comes from built-in parallel execution, flexible test grouping/dependencies, and native data-provider support for parameterized suites -- features JUnit historically needed extensions to match.

Q

Selenium and TestNG experience: how did you structure test scenarios?

intermediate

Tests whether you can describe a concrete structure -- Page Object Model to decouple test logic from locators, TestNG groups/dependencies for execution order, and data providers for data-driven scenarios -- rather than a vague 'we used Selenium with TestNG.'

Q

What is parameterized testing in JUnit?

intermediate

Tests whether you know @ParameterizedTest lets one test method run multiple times with different inputs (via @ValueSource, @CsvSource, or a custom provider), avoiding near-duplicate test methods that differ only in input data.

Q

Difference between @Mock and @Spy in JUnit.

intermediate

Tests whether you know @Mock creates a fully fake object with no real behavior unless stubbed, while @Spy wraps a real object so unstubbed methods execute their actual implementation -- useful when you want to verify interactions on mostly-real behavior.