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.
Java Fundamentals
Why is Java not considered a purely Object-Oriented language?
beginnerJava 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.
How does a Java program actually run, from source file to execution?
beginnerThe .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.
Why is Java called a platform-independent language?
beginnerJava 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.
Why doesn't Java use pointers the way C/C++ does?
beginnerJava 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.
JVM Internals & Memory
What is the difference between Minor GC, Major GC, and Full GC?
intermediateTests whether you know exactly which memory regions each GC type actually sweeps.
What is an OutOfMemoryError vs StackOverflowError?
intermediateTests whether you know these are triggered by two completely different memory regions filling up.
G1 GC vs ZGC vs Shenandoah ā when would you choose each?
advancedTests whether you know the pause-time and throughput tradeoffs across modern collectors, not just their names.
Heap keeps growing even after a Full GC runs. How do you debug it?
advancedTests whether you recognize this as the classic memory-leak signature and know the heap-dump workflow to isolate it.
Production throws OutOfMemoryError: Metaspace. What could cause it?
advancedTests whether you know Metaspace exhaustion usually points to classloader leaks, not regular object allocation.
Java heap is stable, but overall process memory keeps growing. Why?
advancedTests whether you know to look past the heap entirely ā direct ByteBuffers, Netty off-heap memory, or JNI leaks.
Your application pauses frequently, but GC logs look completely normal. What's going on?
advancedTests whether you know JVM safepoints (biased lock revocation, deoptimization) can freeze threads independently of GC.
What is Escape Analysis? Why is it useful?
advancedTests whether you know the JIT can allocate objects on the stack instead of the heap when it proves they never escape a method.
What is the Parent Delegation Model in class loading, and why is it important?
intermediateTests whether you know why a class request always goes up the classloader hierarchy first, and what that prevents.
How do you capture and analyze a heap dump using Eclipse MAT ā what do you actually look for?
advancedTests whether you know the practical workflow: dominator tree, retained size, and finding the actual leak suspect.
What is TLAB (Thread Local Allocation Buffer) and how does it improve allocation performance?
advancedTests whether you know how the JVM avoids lock contention on every single object allocation.
What is GC ergonomics and how does the JVM auto-tune GC settings?
intermediateTests whether you know the JVM picks sensible defaults based on hardware and heap size without any flags at all.
What are the different memory areas in JVM?
beginnerTests whether you know the heap, stack, metaspace, and PC register layout and what lives where.
What is Garbage Collection and how does it work?
intermediateTests whether you understand generational GC, reachability, and why Java doesn't need manual memory management.
What is ClassLoader? Explain the delegation model.
intermediateTests whether you know why a class request is always delegated upward first, and what that prevents.
What is the difference between WeakReference, SoftReference, and PhantomReference?
advancedTests whether you know these three reference types and how each affects when the GC is allowed to reclaim an object.
How does the JIT compiler work?
advancedTests whether you understand how the JVM detects hot code paths and compiles them to native machine code at runtime.
What is Code Cache and what happens when it fills up?
intermediateThe 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.
What does the -XX:+PrintCompilation flag show you?
intermediateIt 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.
What are the performance trade-offs between a 32-bit and 64-bit JVM?
advanced32-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.
What is an escaping reference, and what are the ways to prevent your internal mutable state from leaking to callers?
advancedReturning 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.
How do you tune the String Pool for an application creating millions of unique strings?
advancedThe 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.
What is String Deduplication in G1 GC and how is it different from the String Pool?
advancedString 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.
Why should -Xms and -Xmx be set to the same value in production?
intermediateIf 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.
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.
Why should you never call System.gc() in production code?
beginnerIt'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.
Why is Object.finalize() dangerous, and what should you use instead?
intermediatefinalize() 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.
What is Java Flight Recorder and how is it different from a heap dump?
advancedJFR 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.
Why is naive Java benchmarking (System.nanoTime() around a loop) misleading?
intermediateIt 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.
What is JMH and what does it handle that a hand-rolled benchmark doesn't?
advancedJMH (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.
What is a DirectByteBuffer, and why can it cause OutOfMemoryError even when heap usage looks fine?
advancedByteBuffer.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.
Your Java process consumes 100% CPU ā walk through diagnosing exactly which thread and method is responsible.
advancedUse `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.
What does jcmd VM.native_memory reveal that a heap dump cannot?
advancedA 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.
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?
advancedBy 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.
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.
What tools would you reach for to monitor a Java application's performance in production?
beginnerVisualVM 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.
What is GraalVM and how does its Native Image differ from a standard JVM?
advancedGraalVM 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.
Java Basics & OOP
What is the difference between JDK, JRE, and JVM?
beginnerTests whether you understand the three nested layers of the Java platform and what each one is actually responsible for.
Explain the 4 pillars of OOP with real-world examples.
beginnerChecks whether you can explain encapsulation, abstraction, inheritance, and polymorphism with concrete examples, not just definitions.
What is the difference between == and .equals() in Java?
beginnerTests your understanding of reference equality versus logical equality, and where each one silently trips people up.
What is method overloading vs method overriding?
beginnerTests whether you know compile-time vs runtime polymorphism and the rules that govern each.
What is the difference between abstract class and interface?
beginnerTests whether you know when to use each, especially after Java 8 added default and static methods to interfaces.
Explain the 'static' keyword ā static variable, method, block, class.
beginnerTests whether you understand what 'belongs to the class, not the instance' actually means in memory and execution order.
What is the difference between pass-by-value and pass-by-reference in Java?
beginnerA classic trick question ā tests whether you know Java is always pass-by-value, even for objects, and why that still confuses people.
What is autoboxing and unboxing?
beginnerTests whether you know how Java silently converts between primitives and wrapper classes, and where that costs performance.
What is the diamond problem and how does Java 8 solve it with default methods?
advancedTests whether you understand multiple inheritance ambiguity and the specific resolution rules Java applies for default methods.
Explain how 'instanceof' works and what pattern matching for instanceof (Java 16) does.
advancedTests whether you know the classic instanceof check plus the newer syntax that eliminates the redundant cast afterward.
Does the final keyword make an object immutable?
beginnerNo ā 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.
Why should you never use double for financial calculations?
intermediateBinary 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.
Inner Classes
What are the different types of inner classes in Java ā member, static nested, local, and anonymous?
intermediateTests whether you know all four flavors and what specifically distinguishes each one's scope and use case.
What is the difference between a static nested class and a (non-static) inner class in Java?
intermediateTests whether you know a static nested class doesn't hold an implicit reference to an instance of the outer class, unlike a regular inner class.
What is a local inner class in Java? What are the rules around accessing variables from its enclosing method?
intermediateTests whether you know a local inner class can only capture effectively final local variables from its enclosing scope.
What are anonymous inner classes in Java, and what are their restrictions compared to named classes?
intermediateTests whether you know when this one-off, no-name class syntax is appropriate versus when a lambda or named class fits better.
Collections Framework
What is the difference between List and Set in Java?
beginnerA 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.
What is the difference between HashSet, LinkedHashSet, and TreeSet?
beginnerHashSet 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.
What is the difference between CopyOnWriteArraySet and a regular HashSet?
intermediateCopyOnWriteArraySet 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.
What is the difference between Comparable and Comparator in Java?
beginnerComparable 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.
What is the difference between Collection and Collections in Java?
beginnerCollection (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.
What is the difference between the Collections Framework and the Streams API?
beginnerThe 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.
Explain the Collections hierarchy ā List, Set, Map, Queue.
beginnerTests whether you have a clear mental map of Java's core collection interfaces and how they relate to each other.
How does HashMap work internally? (hashing, buckets, collision)
intermediateOne of the most-asked Java questions ā tests whether you actually understand hashing, bucket placement, and collision resolution, not just usage.
What is the difference between HashMap and Hashtable?
intermediateTests whether you know the thread-safety, null-key, and performance differences between these two legacy-adjacent classes.
How does ConcurrentHashMap differ from HashMap?
intermediateTests whether you understand segment/bucket-level locking and why it beats simply synchronizing a whole HashMap.
A HashMap has millions of entries and suddenly becomes slow. How would you investigate?
advancedTests whether you know to check hashCode() quality, load factor, and whether entries are treeifying due to collisions.
You insert a mutable object as a HashMap key and later modify it. What can go wrong?
advancedTests whether you know a changed hashCode() after insertion makes the entry effectively unfindable at its original bucket.
What is fail-fast vs fail-safe iterator?
intermediateTests whether you know why ConcurrentModificationException happens and which collections avoid it, and how.
Your CopyOnWriteArrayList is creating high memory usage and GC pressure. Why?
advancedTests whether you know every single write copies the entire underlying array, which is brutal for write-heavy or large lists.
Implement an LRU cache using LinkedHashMap.
advancedA very common coding-round question testing whether you know LinkedHashMap's access-order mode and removeEldestEntry hook.
A ConcurrentModificationException occurs in a single-threaded application. How is that possible?
advancedTests whether you know this exception is about structural modification during iteration, not literally about concurrent threads.
What happens when HashMap capacity exceeds load factor? Explain rehashing.
advancedTests whether you understand the resize trigger, the doubling behavior, and why rehashing is expensive.
You're reviewing production code using Collections.synchronizedMap(). Would you keep it or replace it? What factors decide?
advancedTests whether you can weigh whole-map locking against ConcurrentHashMap's finer-grained concurrency for the actual access pattern.
Why can a poor hashCode() implementation destroy HashMap performance?
advancedTests whether you know a constant or low-quality hashCode collapses lookups from O(1) toward O(n) by funneling everything into one bucket.
Two threads call computeIfAbsent() for the same key on a ConcurrentHashMap at the same time. What behavior do you expect?
advancedTests whether you know ConcurrentHashMap guarantees the mapping function runs atomically per key, avoiding duplicate computation.
What is EnumMap and why is it more performant than HashMap for enum keys?
intermediateTests whether you know EnumMap uses ordinal-based array indexing instead of general-purpose hashing.
You need the top 10 most frequent items out of millions of events. Which collections would you combine to solve this efficiently?
advancedTests whether you know to pair a frequency HashMap with a bounded PriorityQueue instead of sorting everything.
A cache should automatically release entries when their keys are no longer strongly referenced elsewhere. What would you use?
advancedTests whether you know WeakHashMap lets the garbage collector reclaim entries whose keys have become otherwise unreachable.
When should you choose ArrayList over LinkedList (and vice versa)?
intermediateAlmost 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.
What are the two mandatory rules for overriding hashCode(), and what breaks if you only override equals()?
intermediateEqual 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.
When would you use TreeMap or LinkedHashMap over a plain HashMap?
beginnerTreeMap 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.
File I/O & NIO
What is the difference between byte streams and character streams in Java I/O ā when do you use InputStream/OutputStream vs Reader/Writer?
intermediateTests whether you know binary data needs byte streams while text data is better handled by character-aware Reader/Writer classes.
What is the difference between FileReader and BufferedReader, and why does wrapping one in the other improve performance?
beginnerTests whether you know buffering reduces the number of expensive underlying I/O calls by reading in larger chunks.
What is the difference between java.io and java.nio? What does NIO's non-blocking, buffer-based model actually change?
advancedTests whether you know NIO's channel/buffer model and selectors enable non-blocking I/O that classic java.io can't do.
Why should file handling code always use try-with-resources instead of manually closing streams in a finally block?
intermediateTests whether you know try-with-resources guarantees close() is called correctly even when multiple exceptions occur, which manual finally blocks often get wrong.
Enums
How do Java enums work internally? What do values(), ordinal(), and valueOf() actually do?
intermediateTests whether you know an enum is really a special class with a fixed set of singleton instances, not just a list of named integers.
Can a Java enum have constructors, fields, and methods? Can each enum constant override a method differently?
intermediateTests whether you know enums are full classes that can carry state and even constant-specific method bodies.
Why are enums a good fit for switch statements and as HashMap/EnumMap keys?
intermediateTests whether you know enums give you type safety and namespace clarity that plain int or String constants don't.
String & StringBuilder
What is String immutability? Why is String immutable in Java?
beginnerTests whether you know the actual design reasons (security, caching, thread safety) behind one of Java's most quoted facts.
What is the String constant pool?
beginnerTests whether you understand where string literals actually live in memory and why that affects == comparisons.
What is the difference between String, StringBuilder, and StringBuffer?
beginnerTests whether you know the mutability and thread-safety tradeoffs behind these three near-identical-looking classes.
Find the longest palindromic substring.
intermediateA classic string DSA problem testing whether you can move from brute force to an efficient expand-around-center or DP approach.
Minimum window substring ā find the smallest window in S containing all characters of T.
advancedTests whether you can apply the sliding-window technique correctly to a genuinely tricky two-pointer problem.
Why can naive string concatenation in a loop hurt performance, and did Java 9 change this?
intermediateStrings are immutable, so `result = result + i` in a loop creates a brand-new String object every iteration ā use StringBuilder instead. Java 9+ does optimize a single-expression concatenation like `"Hello " + name` via invokedynamic to be nearly as fast as StringBuilder, but this doesn't help multi-statement loops.
OOP & Core Syntax
What are the access modifiers in Java, and what does each one control?
beginnerprivate 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.
What is the difference between this and super keywords in Java?
beginnerthis 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.
Can a constructor be declared final or static in Java?
beginnerNo ā 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.
Can you override a private or static method in Java?
beginnerNo. 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).
What is a marker interface in Java? Give an example.
beginnerA 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).
Can you catch multiple exception types in a single catch block?
beginnerYes, 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.
Can you throw a checked exception inside a lambda expression's body?
intermediateOnly 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.
Can you start the same Thread object twice in Java?
beginnerNo ā 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).
Multithreading & Concurrency
Why do Virtual Threads become pinned and lose scalability?
advancedTests whether you know synchronized blocks and native calls can pin a virtual thread to its carrier thread.
What is structured concurrency in Java 21+ and why is it better than raw CompletableFuture chains?
advancedTests whether you know how it ties a group of subtasks' lifetimes together for cleaner cancellation and error handling.
Why are exceptions inside CompletableFuture chains often missed silently?
advancedTests whether you know an unhandled exception in a chain just completes the future exceptionally, with nothing logged unless you check.
ConcurrentHashMap is thread-safe, yet race conditions can still exist in code that uses it. Why?
advancedTests whether you know thread-safety of individual operations doesn't make compound check-then-act sequences atomic.
Why can increasing the thread pool size actually reduce application performance?
advancedTests whether you know excessive threads can increase context-switching overhead and contention beyond a certain point.
What is the difference between synchronized, ReentrantLock, and StampedLock?
advancedTests whether you know the tradeoffs in fairness, interruptibility, and read/write optimization across the three.
What is the difference between CountDownLatch, CyclicBarrier, and Semaphore?
advancedTests whether you know these three synchronization tools solve genuinely different coordination problems.
How does ForkJoinPool differ from a regular ThreadPoolExecutor?
advancedTests whether you know work-stealing is what makes ForkJoinPool efficient for divide-and-conquer tasks specifically.
What happens when you submit too many tasks to a ThreadPoolExecutor ā what are the rejection policies?
advancedTests whether you know the four built-in RejectedExecutionHandler strategies and when each is appropriate.
What is a race condition and how is it different from a data race?
advancedTests whether you know these overlapping-sounding terms actually describe two distinct classes of concurrency bug.
A ThreadLocal variable in your app is causing a memory leak. How does that happen, and how do you fix it?
advancedTests whether you know pooled threads never die, so a ThreadLocal never cleared keeps leaking across every reused thread.
What is the difference between a Thread and a Process?
beginnerTests whether you understand shared vs isolated memory space and why threads are cheaper to create.
What is the difference between wait(), notify(), and notifyAll()?
intermediateTests whether you understand Java's low-level thread coordination primitives and the monitor lock they require.
What is a deadlock? How can you detect and prevent it?
intermediateTests whether you know the four necessary conditions for deadlock and practical strategies to avoid them.
What is the volatile keyword in Java?
intermediateTests whether you know volatile guarantees visibility, not atomicity ā one of the most commonly misunderstood keywords.
What is ExecutorService? How is it better than creating raw threads?
intermediateTests whether you know why managed thread pools beat manually creating and managing Thread objects in production code.
What is a thread-safe Singleton? Implement double-checked locking.
advancedTests whether you can correctly write the volatile + double-checked-locking pattern, a classic concurrency coding question.
What is the Java Memory Model (JMM)? Explain happens-before.
advancedTests whether you understand the formal rules that govern visibility and ordering across threads ā deep concurrency territory.
What is CompletableFuture? How does it differ from Future?
advancedTests whether you know how to chain and combine async operations rather than blocking with Future.get().
Why does volatile guarantee visibility but not atomicity?
intermediatevolatile 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.
How does ConcurrentHashMap achieve thread safety without locking the entire map?
advancedIt 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.
When would you choose LongAdder over AtomicInteger?
advancedUnder 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.
How do you size a ThreadPoolExecutor differently for CPU-bound vs I/O-bound workloads?
intermediateCPU-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.
What's the difference between thenApply(), thenCompose(), and thenCombine() in CompletableFuture?
advancedthenApply() 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.
You receive a production thread dump with hundreds of BLOCKED threads ā how do you identify the root cause?
advancedLook 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.
Arrays & Matrices
What is the difference between Array and ArrayList?
beginnerTests whether you know the fixed-size-vs-dynamic and primitive-vs-object tradeoffs between the two.
Find the maximum subarray sum (Kadane's algorithm).
intermediateTests whether you know the classic O(n) dynamic programming trick, not just a brute-force O(n²) scan.
Sort an array of 0s, 1s, and 2s in a single pass (Dutch National Flag).
intermediateTests whether you can sort in a single O(n) pass with three pointers instead of a generic sort or two passes.
Trapping rainwater problem ā compute how much water can be trapped.
advancedA well-known hard array problem testing two-pointer or prefix-max/suffix-max thinking under a tricky constraint.
Find the longest increasing subsequence (LIS).
advancedTests whether you know both the O(n²) DP solution and the O(n log n) patience-sorting-based approach.
Multithreading Basics
What are the different ways to create a thread in Java?
beginnerExtend the Thread class and override run(), or implement the Runnable interface and pass it to a Thread constructor (preferred, since Java doesn't support multiple inheritance and implementing Runnable keeps the class free to extend something else). A third, more modern approach is submitting a Runnable/Callable to an ExecutorService, which manages the thread lifecycle for you.
What are the different states in a Java thread's lifecycle?
beginnerNEW (created but not started), RUNNABLE (executing or ready to execute ā the JVM doesn't distinguish 'running' from 'ready' as a separate state), BLOCKED (waiting to acquire a lock), WAITING (waiting indefinitely for another thread's signal, e.g. via join() or wait()), TIMED_WAITING (waiting with a timeout, e.g. sleep(ms)), and TERMINATED (finished execution). Thread.getState() returns exactly one of these six values at any point.
What is the difference between Runnable and Callable interfaces in Java?
beginnerRunnable's run() method returns nothing and can't throw a checked exception; Callable's call() method returns a value of a generic type V and CAN throw a checked exception. Callable is submitted to an ExecutorService and returns a Future<V> that lets the caller retrieve the result (or exception) once the task completes.
Functional Programming
What are Method References in Java, and what are the 4 types?
beginnerA 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).
How does Collectors.groupingBy() work in the Stream API? Give an example.
intermediategroupingBy() 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.
What is the Function functional interface in Java, and when do you use it?
beginnerFunction<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.
What is the Predicate functional interface in Java, and when do you use it?
beginnerPredicate<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).
What is the Supplier functional interface in Java, and when do you use it?
beginnerSupplier<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.
What is the Consumer functional interface in Java, and when do you use it?
beginnerConsumer<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.
What are the BiFunction, BiPredicate, and BiConsumer functional interfaces?
beginnerThey 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.
What are UnaryOperator and BinaryOperator, and how do they differ from Function and BiFunction?
intermediateUnaryOperator<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).
What are primitive functional interfaces in Java, and why do they exist?
intermediatePrimitive 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.
What does the Stream filter() method do, and how is it different from map()?
beginnerfilter() 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.
What does the Stream collect() method do, and what's the difference between collect() and forEach()?
beginnercollect() 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.
What does the Stream distinct() method do, and how does it determine uniqueness?
beginnerdistinct() 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.
What do the Stream limit() and skip() methods do?
beginnerlimit(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.
What does the Stream count() method do, and how does it interact with filter()?
beginnercount() 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.
What is the difference between anyMatch(), allMatch(), and noneMatch() in the Stream API?
beginnerAll 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
What are the key features introduced in Java 8?
beginnerTests whether you can name and briefly explain lambdas, streams, Optional, and the new Date/Time API.
What is a functional interface? Can you write a custom one?
beginnerTests whether you understand the single-abstract-method rule that makes lambda expressions possible.
What is the difference between map() and flatMap() in Streams?
intermediateTests whether you understand when a stream operation needs to flatten nested structures, not just transform elements.
What is the Optional class? How does it prevent NullPointerException?
beginnerTests whether you know how to use Optional correctly, and the common anti-patterns that misuse it.
What is the difference between lazy and eager evaluation in Streams? Explain with an example.
advancedTests whether you understand that intermediate operations don't execute until a terminal operation triggers the pipeline.
When can a Stream pipeline actually be slower than a plain for-loop?
advancedFor small collections or complex multi-step transformations, Stream's pipeline setup overhead can exceed a simple loop's cost ā one real benchmark showed a complex stream at 174ms versus a plain loop's baseline, while a parallelStream() version was actually the fastest at 23ms when CPU cores were available.
Exception Handling
What is the difference between checked and unchecked exceptions?
beginnerTests whether you know which exceptions the compiler forces you to handle and why that distinction exists.
What is try-with-resources? How does it differ from traditional try-catch-finally?
intermediateTests whether you know how AutoCloseable resources get closed automatically, and in what order during suppressed exceptions.
How do you create a custom exception? Give checked and unchecked examples.
intermediateTests whether you can design exception classes correctly and know when each type is the right choice.
What is exception chaining?
advancedTests whether you know how to preserve the original cause when wrapping and rethrowing a different exception type.
What is the difference between ClassNotFoundException and NoClassDefFoundError?
advancedTests whether you know these are thrown at different times for different reasons, despite sounding like the same problem.
Modern Java (11-25)
Are Java Records truly immutable? What are their limitations?
intermediateTests whether you know records give you shallow immutability for their own fields, not deep immutability of referenced objects.
What are Sealed Classes in Java 17 ā how do they enforce domain modeling?
intermediateTests whether you know sealed types let you declare an exhaustive, closed set of permitted subtypes at compile time.
What is Pattern Matching for switch (Java 21) and how does it improve type-safe branching?
intermediateTests whether you know how it eliminates the manual instanceof-and-cast boilerplate switch statements used to require.
What are Sequenced Collections in Java 21?
intermediateTests whether you know this new interface finally gives a consistent way to access first/last elements across ordered collection types.
How does Java 21's virtual thread implementation handle blocking I/O internally ā what is carrier thread pinning?
advancedTests whether you understand the mechanism that lets thousands of virtual threads share a small pool of OS carrier threads.
What is the difference between var (Java 10) and explicitly typed declarations ā when does var hurt readability?
intermediateTests whether you know var is fine when the type is obvious from context, but can obscure intent when it isn't.
Java 25 Compact Object Headers (JEP 519) ā what does it mean for production workloads?
advancedTests whether you're current on recent JVM changes and know what shrinking object headers actually saves in practice.
DSA ā Problem-Solving Patterns
What is the Sliding Window pattern in DSA, and what class of problems does it solve efficiently?
intermediateTests whether you can recognize when a shrinking/growing window beats a brute-force nested loop.
What is the two-pointer pattern? Give an example problem where it turns an O(n²) solution into O(n).
intermediateTests whether you know how converging pointers from both ends of a sorted structure eliminate redundant comparisons.
What is the fast & slow pointers pattern? How does it detect a cycle in a linked list?
intermediateTests whether you know Floyd's algorithm and why two pointers moving at different speeds must eventually meet in a cycle.
What is the merge intervals pattern? Walk through merging a list of overlapping intervals.
intermediateTests whether you know to sort by start time first, then merge in a single linear pass.
What is the Top K Elements pattern using a heap, and why is it more efficient than sorting the entire dataset?
advancedTests 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.
What is the 0/1 Knapsack dynamic programming pattern, and what other problems share its structure?
advancedTests whether you can recognize the include-or-exclude decision structure that generalizes to many DP problems.
What is the topological sort graph pattern? How does it apply to a course-scheduling / build-order problem?
advancedTests whether you know how to order nodes in a DAG so every dependency is processed before what depends on it.
Find the Kth largest element in a stream of numbers, where new numbers keep arriving.
advancedTests whether you know to maintain a fixed-size min-heap instead of re-sorting on every new element.
Implement an LFU (Least Frequently Used) Cache with O(1) get and put.
advancedTests whether you can design a harder variant of LRU that also tracks access frequency, not just recency.
Find the median from a data stream ā numbers keep arriving one at a time, and you must return the median at any point.
advancedTests whether you know the two-heap technique (a max-heap and a min-heap balanced against each other) for this classic problem.
Solve the Word Ladder problem ā find the shortest transformation sequence from one word to another, changing one letter at a time.
advancedTests whether you know to model this as a graph shortest-path problem and solve it with BFS.
DSA ā Lists, Stacks & Queues
Reverse a Singly Linked List
intermediateOne of the most common coding-round openers ā tests whether you can manipulate pointers correctly without losing the list.
Detect a loop in a Linked List
intermediateTests whether you know Floyd's cycle detection (slow/fast pointer) technique.
LRU Cache implementation
advancedTests whether you can combine a hash map and a doubly linked list to get O(1) get/put with eviction.
DSA ā Trees & Graphs
Binary Tree Traversals
intermediateTests whether you can implement preorder, inorder, postorder, and level-order traversal, iteratively and recursively.
Validate a Binary Search Tree (BST)
intermediateTests whether you know the common mistake of only checking immediate children instead of the full valid range.
Dijkstra's Shortest Path Algorithm
advancedTests whether you can implement the classic priority-queue-based shortest path algorithm and explain its greedy correctness.
Topological Sort
advancedTests whether you know how to order a DAG's nodes using DFS-based or Kahn's BFS-based approach.
Design Patterns & SOLID
Singleton Pattern
beginnerTests whether you can implement Singleton correctly and know the ways it can accidentally be broken.
Builder Pattern vs Telescoping Constructor
beginnerTests whether you know when a growing list of constructor parameters should become a Builder instead.
SOLID Principles overview
intermediateTests whether you can name and briefly explain all 5 SOLID principles with a one-line example each.