ā˜•

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

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.

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

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 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

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

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 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

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.

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.

Inner Classes

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

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

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

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

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

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

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

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

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.

File I/O & NIO

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).

Multithreading & Concurrency

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 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

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

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

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

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

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

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

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.

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.