A Java interview should connect language rules to the behavior of real programs. A developer needs to explain why two objects compare differently, how a collection handles its elements, what an exception changes, and when shared state is safe. Short coding exercises are most useful when candidates can justify the result and identify the assumptions behind it.
This guide to 100+ Java Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It covers object-oriented design, types, collections, generics, streams, concurrency, JVM concepts, and practical coding. Java 21 is the example baseline; release-dependent features are identified rather than presented as available in every Java environment.
How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Java interviews?
Java interviews often combine a small coding task with questions about object contracts, collection choices, or concurrent execution. A candidate should be able to trace the program, explain a trade-off, and adapt the solution when a requirement changes. Unauthorized real-time assistance can make that independent understanding harder to assess.
Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during Java developer interviews.
Pair interview-integrity checks with a clearly specified programming task. Add a duplicate value, change the equality requirement, or introduce concurrent callers, then ask the candidate to predict the effect and propose a focused test. Review suspicious activity in context rather than treating a signal as proof of misconduct.
Java Interview Questions
Choose questions that match the role’s language, library, concurrency, and design responsibilities. State the Java release and relevant input or execution assumptions. Ask candidates to explain correctness and resource ownership before discussing convenience or performance.
Java Interview Questions for Beginners
These beginner questions cover the Java platform, values and references, classes, methods, object-oriented concepts, strings, exceptions, and basic collections. They test whether a candidate can read a small program and explain its behavior without relying on memorized output alone.
What roles do the JDK, JVM, and runtime libraries play in running a Java application?
How does Java portability work, and what can still make an application platform-dependent?
How do primitive values differ from reference values in Java?
What does Java pass-by-value mean when a method receives an object?
How do local variables, instance fields, and static fields differ in initialization and lifetime?
When would you use final, and why does a final reference not make its object immutable?
How do public, protected, package-private, and private access differ?
How do encapsulation, inheritance, abstraction, and polymorphism work together in Java?
How are constructors different from ordinary methods, and what does constructor chaining do?
How does method overloading differ from method overriding?
When should a Java type be an interface rather than an abstract class?
How do static methods and fields differ from instance members?
When is composition a better choice than inheritance in Java?
What is the difference between == and equals() for Java objects?
Why must equals() and hashCode() be designed together?
Why is String immutable, and how do string literals relate to the string pool?
When should you use StringBuilder instead of repeated string concatenation?
How do arrays and ArrayList differ in typing, size, and access?
How do List, Set, Queue, and Map represent different collection needs?
When would you choose ArrayList rather than LinkedList?
How do HashMap, LinkedHashMap, and TreeMap differ in ordering and cost?
How would you remove duplicates from a list while preserving first-occurrence order?
What safety do generics add, and why should raw collection types usually be avoided?
What are autoboxing and unboxing, and when can they change program behavior?
How do checked exceptions, unchecked exceptions, and Error differ?
What is the difference between throw and throws?
How do try, catch, and finally interact when control leaves a block?
How does try-with-resources close resources and preserve multiple exceptions?
What is a functional interface, and how does a lambda implement one?
How does a stream pipeline differ from a collection?
How does Optional communicate absence, and how should callers consume it?
How would you write a palindrome check with an explicit character-handling policy?
How would you count word frequencies using a Map?
How does an enum improve a model compared with unrelated integer constants?
What does a record generate, and why is record immutability only shallow?
How do byte streams, character readers, and character encodings differ?
How would you read a small UTF-8 text file and handle ownership of its resources?
How do Instant, LocalDate, and ZonedDateTime represent different time concepts?
How do creating a Thread and submitting a task to an ExecutorService differ?
How would you test a small Java function using normal, boundary, and invalid inputs?
Java Interview Questions for Intermediate
These intermediate questions examine collection contracts, generics, functional operations, exceptions and resources, concurrency tools, and modern language features. They ask candidates to choose an implementation and explain its edge cases.
How do wildcard bounds express producer and consumer roles in a generic API?
How does type erasure affect overloads, runtime checks, and generic arrays?
When should a method declare a type parameter instead of accepting an unbounded wildcard?
How would you sort objects by multiple fields with a clear null policy?
How do Arrays.asList, List.of, and List.copyOf differ in mutability and aliasing?
How should a collection be modified during iteration without relying on fail-fast behavior?
How would you implement a bounded least-recently-used cache with LinkedHashMap?
How would you find the k largest integers without sorting the entire input?
How do map() and flatMap() differ for Stream and Optional?
When should a stream use reduce() rather than collect()?
How would you group objects and compute a per-group total with collectors?
How should Collectors.toMap handle duplicate keys?
Why must stream lambdas be non-interfering, and what makes a parallel stream safe or worthwhile?
How do primitive streams help avoid boxing in numeric pipelines?
How do pattern matching for instanceof and switch simplify type-dependent logic in Java 21?
How would you model a closed family of outcomes using sealed types and records?
How do compact record constructors validate and defensively copy components?
When are nested static classes, inner classes, and local classes appropriate?
How do default methods resolve conflicts between interfaces?
How do annotations and reflection support runtime behavior, and what limits access?
How do package boundaries and Java modules differ in encapsulation?
How would you design and translate exceptions at a service boundary without losing the cause?
How would you process a large text file without loading it all into memory?
How would you make a time-dependent Java service deterministic in tests?
How do synchronized and ReentrantLock differ in capabilities and cleanup requirements?
What does volatile guarantee, and why is volatile count++ not atomic?
How do Callable, Future, and CompletableFuture represent task results?
How do thenApply and thenCompose differ when composing CompletableFuture operations?
How would you size and bound an executor's work queue and choose a rejection policy?
How should Java tasks cooperate with cancellation and interruption?
How does ConcurrentHashMap support atomic per-key updates without making multi-step workflows atomic?
How would you coordinate a bounded producer-consumer pipeline using BlockingQueue?
What are virtual threads in Java 21, and which workloads benefit from them?
How do heap storage, JVM stacks, and metaspace differ?
What happens during class loading, linking, and initialization?
How do interpretation and JIT compilation affect performance and warm-up?
What makes an object eligible for garbage collection, and why is collection timing nondeterministic?
How would you implement binary search with an unambiguous result contract?
How would you merge two sorted integer arrays while retaining duplicates?
How would you implement value equality for a class with array fields?
Java Interview Questions for Experienced
These experienced-level questions focus on API design, concurrent correctness, JVM behavior, resource management, compatibility, and demanding coding trade-offs. They assess whether a developer can reason from explicit guarantees and evidence under realistic constraints.
How does the Java Memory Model use happens-before to make shared state visible?
How can immutable state be safely published, and what does final-field semantics not guarantee?
How would you design a thread-safe lazy singleton, and when is double-checked locking valid?
How would you protect an invariant that spans multiple variables or map entries?
When should you use AtomicInteger, LongAdder, or a lock for shared counters?
How would you prevent deadlock when an operation must acquire two account locks?
How do CompletableFuture timeouts, cancellation, and exception handlers affect underlying work?
How would you limit downstream concurrency when using virtual-thread-per-task execution?
Why do ThreadLocal usage and blocking code deserve a fresh review when migrating to virtual threads?
How would you choose between a parallel stream, a bounded platform-thread executor, and virtual threads?
How would you design a cache that avoids duplicate loads without holding a global lock during I/O?
How do equality, ordering, and mutability interact when objects are keys in hash-based or sorted maps?
How would you expose a stable public generic API without leaking mutable implementation details?
What are the tradeoffs of using records as public API or persistence models?
How does evolving a sealed hierarchy affect exhaustive switch clients and binary compatibility?
How can a class-loader boundary make identically named classes different types?
What do allocation rate, live-set size, pause goals, and throughput imply for garbage-collector selection?
How can object layout, boxing, and collection choice change the memory cost of an algorithm?
How would you design a streaming aggregation that remains memory-bounded as input grows?
How would you implement a top-k frequency result with deterministic tie-breaking?
How would you implement and test a stable deduplication method with a caller-supplied key extractor?
How would you implement a bounded batch iterator without dropping or duplicating elements?
How would you design an immutable aggregate containing mutable collections and byte arrays?
How can dependency injection through constructors improve testability without a framework?
How would you test concurrent code without depending on arbitrary sleep durations?
How would you verify equals, hashCode, and Comparator contracts with generated and boundary cases?
How would you measure a Java optimization without confusing JIT effects, dead-code elimination, or GC with speedup?
How should a Java API distinguish invalid input, absent data, and operational failure?
How would you preserve numeric correctness when calculating money or other decimal quantities?
How would you handle Unicode text when char-by-char processing is not sufficient?
How would you separate elapsed-time measurement from wall-clock and calendar calculations?
How do Path resolution, normalization, and filesystem checks differ when handling a user-provided filename?
How should an API transfer ownership of streams, executors, or other AutoCloseable resources?
What risks come with native Java serialization, and when should a versioned data format be preferred?
When would ServiceLoader be preferable to hard-coded construction or reflective class names?
How do dynamic proxies differ from subclass-based interception in their method coverage?
How would you make a collection-processing API explicit about ordering, nulls, duplicates, and parallelism?
How would you design a retry loop with bounded attempts, backoff, and cancellation?
How would you evolve a library while preserving source, binary, and behavioral compatibility?
How would you review a Java 21 solution before adopting a newer supported JDK release?
Java Interview Questions and Answers
The answers follow the question bank in order and connect language rules and API contracts to practical examples. Some snippets are focused methods or class excerpts rather than standalone programs. Use their stated imports and context, and distinguish a specified guarantee from an implementation detail or an observation from one execution.
Java Interview Questions and Answers for Beginners
The beginner answers establish the core terminology and show how common language features behave. They make object identity, value comparisons, control flow, and simple coding assumptions explicit.
1. What roles do the JDK, JVM, and runtime libraries play in running a Java application?
The JDK supplies development tools, including javac, together with a Java runtime. javac normally translates .java source into .class files containing bytecode. The JVM loads and verifies those classes and executes their instructions; a JVM implementation may interpret code and compile frequently used code to native instructions.
Runtime libraries provide the platform APIs the application calls, such as String, collections, file handling, and concurrency utilities. They are not the JVM instruction set itself. Running an application needs a compatible runtime and its dependencies, not necessarily the compiler. Deployment can use a full JDK or an appropriately constructed runtime image; a separate standalone JRE installation is not a universal modern requirement.
2. How does Java portability work, and what can still make an application platform-dependent?
Java portability comes from targeting a specified class-file format and JVM behavior rather than a particular CPU instruction set. A compatible JVM implementation translates that execution model to its operating system and hardware. The same application bytecode can therefore run across platforms when its Java version and dependencies are supported.
Portability is not automatic for everything around that bytecode. JNI libraries need platform-specific binaries; absolute filesystem paths, case sensitivity, native commands, permissions, locale, and available fonts can differ. External services and environment variables also remain deployment dependencies. Use platform APIs such as Path, specify text encodings at boundaries, and test on supported target systems. A Java 21 class file does not become runnable on Java 17 merely because both systems have a JVM.
3. How do primitive values differ from reference values in Java?
A primitive variable holds a value of one of eight types: byte, short, int, long, char, float, double, or boolean. A reference variable holds a reference to an object or the special null value. Classes, interfaces, and arrays are reference types; String is not a primitive.
Assigning an int copies its numeric value. Assigning an object reference copies the reference, so two variables can refer to the same mutable object. Changing that object's state is visible through both references; reassigning one variable does not reassign the other. Primitives cannot be null, whereas dereferencing a null reference can throw NullPointerException. These language distinctions should not be reduced to a universal “primitives on stack, objects on heap” physical-layout rule.
4. What does Java pass-by-value mean when a method receives an object?
Java always passes arguments by value. For an object argument, the copied value is its reference, not a copy of the object. The caller's variable and the parameter initially refer to the same object, so a method can mutate that shared object. Assigning a different reference to the parameter changes only the method's local parameter variable.
This program prints changed, not replacement. The first operation updates the caller-visible builder; the second merely redirects value inside update. The same rule applies to arrays and user-defined objects. A method that must replace the caller's value should return the replacement for the caller to assign, rather than attempting to reassign its parameter.
Java example
5. How do local variables, instance fields, and static fields differ in initialization and lifetime?
A local variable belongs to a particular method invocation or block. It receives no automatic default value that permits reading it: the compiler requires definite assignment before use. Its lexical scope is also different from the lifetime of an object it references; that object can remain reachable after the method returns.
An instance field belongs to each object. A static field belongs to the class represented at runtime, shared by that class's instances. Fields first receive defaults such as zero, false, or null, before applicable initializers and constructor work. A class can be loaded separately by different class loaders, producing distinct static state. Static fields are not necessarily process-eternal: eligible classes and their defining loaders can eventually be unloaded.
6. When would you use final, and why does a final reference not make its object immutable?
Use final when a variable should receive one assignment, a method should not be overridden, or a class should not be subclassed. A final variable can be initialized later where definite-assignment rules permit, such as a final instance field assigned in a constructor.
For a reference, final fixes which object the variable refers to; it does not freeze that object's contents. This final list can still accept another element. Its variable cannot then be assigned a different list. Immutable design additionally controls all reachable mutable state, often using defensive copies and avoiding mutating methods. Neither a final reference nor an unmodifiable collection wrapper automatically makes mutable elements immutable or makes compound operations thread-safe.
Java example
7. How do public, protected, package-private, and private access differ?
Access modifiers establish who can use a declaration; they do not change whether a reference can point to an object.
Access | Basic member accessibility |
|---|---|
| Accessible wherever the enclosing type is accessible, subject to module boundaries. |
| Same package, plus qualifying subclass access outside the package. |
Package-private | Same package; written with no access modifier. |
| Within the enclosing top-level class or interface's nest of declarations. |
The important protected nuance is cross-package instance access: a subclass cannot use an arbitrary superclass-typed reference to access the protected member. The qualifying expression must have that subclass's type or a subtype. Top-level classes cannot be private or protected. Prefer the narrowest access that supports the intended API; package-private is useful for internal collaboration without publishing implementation details.
8. How do encapsulation, inheritance, abstraction, and polymorphism work together in Java?
Consider a payment model. An interface such as PaymentMethod exposes pay(amount) without exposing how each provider works: that is abstraction. A wallet implementation keeps its balance private and validates withdrawals through methods: that is encapsulation, because callers cannot bypass its invariants by writing the field directly.
A specialized wallet might inherit carefully designed shared behavior from a base wallet: that is inheritance. Checkout code can hold a PaymentMethod reference and invoke pay; the actual implementation supplies the behavior: that is polymorphism through dynamic instance-method dispatch.
These ideas reinforce each other but do not require a deep class hierarchy. Multiple unrelated implementations can satisfy the same interface, and composition often reuses behavior without exposing superclass details or weakening invariants.
9. How are constructors different from ordinary methods, and what does constructor chaining do?
A constructor initializes a newly created instance. It has the class's name, no return type, and is not inherited or overridden. Ordinary methods have a return type, including void, and can be invoked repeatedly after construction. Constructors can be overloaded with different parameter lists.
Constructor chaining centralizes initialization. this(...) invokes another constructor in the same class; super(...) invokes a constructor in the direct superclass. Under the Java 21 baseline, an explicit constructor invocation must be the first statement. If neither is written, the compiler normally inserts super(), which must be accessible and applicable. A constructor chain cannot be recursive. The compiler supplies a default constructor only when the class declares no constructor; declaring a parameterized constructor does not also generate a no-argument one.
10. How does method overloading differ from method overriding?
Overloading uses the same method name with different parameter signatures. The compiler chooses an applicable overload using the declared types of the receiver and arguments. Changing only a return type does not create an overload.
Overriding supplies a subclass implementation of an inherited instance method. Once a signature has been selected, dynamic dispatch chooses the implementation for the receiver's runtime class. Overrides cannot reduce access and have restrictions on checked exceptions; covariant reference return types are allowed.
Here value is declared Object, so overload resolution selects pick(Object), even though its object is a string. The receiver is a Child, so its override runs. Calling with the literal selects pick(String) instead. Static methods are hidden, not dynamically overridden.
Java example
11. When should a Java type be an interface rather than an abstract class?
Use an interface to describe a capability that unrelated classes can provide, such as ordering, storage, or message delivery. A class can implement multiple interfaces while extending only one class. This keeps consumers dependent on a contract rather than one implementation family.
Use an abstract class when closely related implementations need shared instance state, constructor-enforced invariants, protected helpers, or a common partial implementation. Its cost is coupling subclasses to that superclass and consuming their single superclass choice.
Modern interfaces are not limited to abstract method declarations: they can contain default instance methods, static methods, and private helpers. They still have no instance fields or constructors; interface fields are implicitly public static final. Default methods support behavior reuse but do not replace stateful base-class construction.
12. How do static methods and fields differ from instance members?
An instance member operates on a particular object. Each object has its own instance fields, and instance methods can use this to reach that state. A static member belongs to the runtime class rather than a particular instance. A static method has no this, though it can access an object's members through an explicit reference.
Use static methods for operations whose contract does not require receiver state, such as a conversion helper, and static fields for genuine class-level data. Mutable static data can introduce hidden coupling and needs appropriate concurrency control. Static methods are selected through compile-time type information and can be hidden by subclasses, not overridden. Static state is per runtime class identity, not an unconditional singleton across different defining class loaders.
13. When is composition a better choice than inheritance in Java?
Composition is preferable when one object uses another's behavior but should not be substitutable for it. A report service can hold a formatter and a storage interface; it does not need to extend a formatter or storage implementation. Different collaborators can then be supplied without changing the report service's superclass.
This limits exposure to superclass internals and makes dependencies explicit. It also avoids inheriting unrelated operations: a stack backed by a list should not necessarily expose every list mutation. The tradeoff is some delegation code and the need to define suitable collaborator contracts.
Inheritance remains appropriate for a genuine subtype whose behavior preserves the parent's promises, especially when the base class was designed for extension. Reusing a few methods alone is not enough justification for a subclass.
14. What is the difference between == and equals() for Java objects?
For object references, == checks identity: whether both refer to the same object, or both are null. equals() invokes the type's equality operation. The implementation inherited from Object also uses identity, but types such as String override it to compare logical contents.
The two strings below contain the same characters but were explicitly constructed as distinct objects, so identity is false and string equality is true. Objects.equals(a, b) handles nulls: it returns true for two nulls and otherwise delegates appropriately. Calling a.equals(b) when a is null throws NullPointerException. Do not let string interning or wrapper caching turn identity into a substitute for value comparison. For arrays, ordinary equals() still uses identity; choose an appropriate Arrays.equals overload for element comparison.
Java example
15. Why must equals() and hashCode() be designed together?
Hash-based collections use a hash to narrow their search and equality to identify a matching key or element. Therefore, equal objects must have equal hash codes. Unequal objects may share a hash code; a collision is permitted and must not be treated as equality.
If a type overrides equals() using an account ID but retains identity-based hashing, two logically equal instances can be routed inconsistently in a HashMap or HashSet. Define both operations from the same stable equality-relevant state. Equality should also be reflexive, symmetric, transitive, consistent, and false for null.
Avoid changing a key's equality or hash-relevant fields while it is stored in a map. An immutable key, or an immutable snapshot of those fields, makes the collection contract much easier to preserve.
16. Why is String immutable, and how do string literals relate to the string pool?
A String object's character sequence cannot change after construction. Operations such as replace and concatenation return a result rather than editing the original string. Reassigning a variable to that result changes the reference, not the original object. Immutability lets strings be shared safely and keeps their content-based equality and hashing stable.
String literals and string-valued constant expressions are interned: equal constant strings share a canonical instance. Thus "ja" + "va" == "java" is true because the concatenation is a compile-time constant. new String("java") explicitly creates a different object, although it has equal contents. intern() returns the canonical pooled representative. Pooling is an implementation of sharing, not a reason to use == for application-level string comparisons; use equals() instead.
17. When should you use StringBuilder instead of repeated string concatenation?
Use StringBuilder when constructing one result through repeated additions, especially a loop whose number of additions depends on the input. It maintains a mutable sequence, avoiding a succession of growing immutable intermediate strings. For a bounded number of ordinary concatenations, + is often clearer; compilers and runtimes can optimize concatenation, so replacing every + mechanically is not justified.
This example builds 1,2,3 without a leading or trailing separator. The work is proportional to the characters appended, with capacity growth amortized; the result itself requires space proportional to its length. An empty input would produce an empty string. StringBuilder is not synchronized, so keep a builder confined to one operation or arrange external coordination rather than sharing it unsafely across threads.
Java example
18. How do arrays and ArrayList differ in typing, size, and access?
An array has a fixed length and can store primitive values directly, such as int[], or object references. ArrayList<E> is resizable and stores references; numeric elements therefore use wrapper types such as Integer. Both provide constant-time indexed access, while ArrayList append is amortized constant time and middle insertions or removals require shifting elements.
Arrays are covariant: a String[] can be assigned to Object[], but storing an incompatible object through that reference throws ArrayStoreException. Generic lists are invariant: List<String> is not a subtype of List<Object>, so the analogous unsafe assignment is rejected during compilation.
Use arrays for fixed-size, primitive-heavy storage or APIs that require them. Use ArrayList for a convenient growing sequence. Array length is .length; list element count is .size().
19. How do List, Set, Queue, and Map represent different collection needs?
Choose the abstraction from the data contract rather than from a familiar implementation name.
Abstraction | Main contract | Example need |
|---|---|---|
| Ordered sequence, indexed access, duplicates allowed | An editable itinerary |
| No duplicate elements according to its equality rules | Unique registered IDs |
| Elements waiting for processing; ordering depends on implementation | FIFO jobs or priority work |
| Keys associated with values; one mapping per key | Account lookup by ID |
Map is not a subtype of Collection; its keys, values, and entries are exposed through collection views. Ordering, null support, concurrency, and mutation support vary by implementation. A HashSet does not promise iteration order, and a priority queue is not simply FIFO. Select those details explicitly rather than assuming every implementation shares them.
20. When would you choose ArrayList rather than LinkedList?
Choose ArrayList for most general list workloads, especially indexed reads, iteration, and appending. Indexed access is constant time, appending is amortized constant time, and its backing array avoids a separate linked node for each element. Its compact reference layout can also be favorable for iteration, although actual performance depends on the workload and runtime.
LinkedList needs linear traversal to reach an arbitrary index, starting from the nearer end. An insertion or removal can be constant time after an iterator has reached the position, but locating that position is not free. Repeatedly calling get(i) inside a loop is therefore a poor traversal strategy for it.
For frequent queue or stack operations at the ends, also consider ArrayDeque; needing a queue does not by itself imply needing a linked list.
21. How do HashMap, LinkedHashMap, and TreeMap differ in ordering and cost?
The choice depends on whether order is irrelevant, encounter-based, or sorted.
Implementation | Iteration order | Typical lookup/update cost |
|---|---|---|
| No order guarantee | Expected constant time with well-dispersed hashes |
| Normally insertion order; optionally access order | Expected constant time with well-dispersed hashes |
| Key order from natural ordering or a comparator | Guaranteed logarithmic |
Replacing an existing value in an ordinary insertion-ordered LinkedHashMap does not move the key. An access-ordered map deliberately changes order on specified accesses, which is useful for cache policies. TreeMap treats keys as equivalent when their comparison returns zero, so its ordering should be consistent with equals() to satisfy the general map contract. None of these choices makes mutable keys safe or supplies general thread safety.
22. How would you remove duplicates from a list while preserving first-occurrence order?
Construct a LinkedHashSet from the list, then copy its elements into a new list. The set removes duplicates using equals() and hashCode() while retaining the first encounter of each distinct element. Copying it into an ArrayList gives the caller a separately mutable result and leaves the input list unchanged.
This contract rejects a null list but permits null elements; repeated nulls become one null at their first position. It is case-sensitive for strings: "A" and "a" are different values. For n input elements and u distinct values, expected time is O(n) with suitable hashing and auxiliary space is O(u). The copy is shallow, so mutable element objects remain shared and should not change equality during processing.
Java example
23. What safety do generics add, and why should raw collection types usually be avoided?
Generics let the compiler check relationships between types before the program runs. A List<String> accepts strings and returns a String from get, so callers do not need repeated casts. List<int> is invalid because type arguments must be reference types; use List<Integer> for boxed integers.
A raw List discards those element-type checks for legacy interoperability. An unchecked operation can insert the wrong element into a list that other code treats as typed, allowing a later compiler-inserted cast to fail with ClassCastException. Warnings identify this weakened guarantee; they are not harmless decoration.
The example's commented insertion would fail compilation. Generics do not make the list immutable or validate business rules such as whether a name is blank, but they eliminate an important category of accidental type mixing.
Java example
24. What are autoboxing and unboxing, and when can they change program behavior?
Autoboxing converts a primitive value to its wrapper reference, such as int to Integer. Unboxing retrieves the primitive value from a wrapper. These conversions make APIs such as List<Integer> convenient, but they add reference semantics and possible nulls to otherwise primitive-looking code.
Unboxing null throws NullPointerException: Integer count = null; int n = count; fails. Comparing two Integer references with == checks identity, not their numbers. Some boxed values are cached, so small-value examples can misleadingly appear correct; use value-based equality or deliberate primitive comparison.
Overload selection can also be surprising: list.remove(1) removes the element at index 1 from a List<Integer>, while list.remove(Integer.valueOf(1)) removes the first equal value. Boxing can also add memory and processing overhead in numeric-heavy collections.
25. How do checked exceptions, unchecked exceptions, and Error differ?
All throwable objects derive from Throwable. Checked exceptions are exception types outside the unchecked families; a method must catch them or declare that they may propagate when the language's exception analysis requires it. IOException is a common example.
Unchecked exceptions include RuntimeException and its subclasses, such as IllegalArgumentException, and also Error and its subclasses. They do not require catch-or-declare treatment. An Error, such as OutOfMemoryError, normally signals a serious condition for which ordinary application recovery is not expected.
This classification is a compile-time contract, not a perfect recoverability scale: some runtime exceptions can be handled meaningfully, and not every checked failure can be recovered locally. Catch exceptions where the program can take a useful action; do not broadly catch Throwable merely to hide failures.
26. What is the difference between throw and throws?
throw is an executable statement that raises a particular throwable object and abruptly transfers control to exception handling. throws is part of a method or constructor declaration: it lists exception types that may propagate to callers. A declaration alone does not cause an exception, and a method may declare a checked exception without throwing it on every invocation.
Here parsePort either returns a validated integer or throws InvalidPortException. Because that type extends Exception rather than RuntimeException, callers must handle or declare it. The method translates malformed numeric text into its own public failure contract and preserves the original cause. The allowed range is explicit: 1 through 65,535, with no surrounding whitespace accepted. Valid input prints 8080; the second call reports its range failure.
Java example
27. How do try, catch, and finally interact when control leaves a block?
A try block runs until it completes normally or control leaves it, for example through an exception or return. When an exception is thrown, the first compatible catch handles it; place more specific catches before broader ones. A finally block then runs during ordinary control transfer, including a pending return or propagating exception.
If finally completes normally, the earlier outcome continues. If it throws or returns instead, that new abrupt outcome replaces the earlier one. For example, returning from finally can silently discard a useful exception. Avoid that pattern and use try-with-resources for resource cleanup.
“Finally always runs” is too strong: process termination, a JVM crash, or a computation that never leaves the protected block can prevent it. It is a language control-flow guarantee, not a durable shutdown mechanism.
28. How does try-with-resources close resources and preserve multiple exceptions?
Try-with-resources takes ownership of declared AutoCloseable resources for the statement and closes successfully initialized resources in reverse declaration order. It handles normal completion and exceptions without handwritten finally blocks. If a later resource fails to initialize, earlier successfully initialized resources are still closed.
When the body throws and closing also throws, the body exception remains primary and close failures are attached as suppressed exceptions. If the body succeeds, the first failing close becomes primary and subsequent close failures are suppressed. This preserves multiple failures instead of replacing the original one.
The example deliberately makes both closes fail. It prints close order B, then A; body remains the caught exception, with B and A in its suppressed list. Production cleanup code should avoid throwing unnecessarily.
Java example
29. What is a functional interface, and how does a lambda implement one?
A functional interface represents one abstract operation, allowing for inherited override-equivalent declarations and excluding signatures matching public methods of Object. It may also contain default, static, and private methods without adding another abstract operation. @FunctionalInterface is optional, but it asks the compiler to verify that the declaration qualifies.
A lambda supplies behavior for that operation in a target functional-interface type. The compiler checks its parameter and return types against the target. Here Predicate<String> expects boolean test(String), so the lambda tests whether a value is a non-null, nonblank string.
The local variable minimum is captured. Captured local variables must be final or effectively final; they cannot be reassigned after initialization. That restriction concerns the captured variable, not deep immutability of any referenced object.
Java example
30. How does a stream pipeline differ from a collection?
A collection stores elements; a stream describes a computation over a source such as a collection, an array, or generated values. Intermediate operations such as filter and map are lazy: they assemble a pipeline rather than immediately traversing the source. A terminal operation initiates consumption and produces a result or side effect.
The example filters positive integers, doubles them, and materializes [6, 4]. It does not change the input list. In Java 21, Stream.toList() returns an unmodifiable list, so callers must not assume the result supports add.
A stream is single-use, unlike a collection that can be traversed again. Create a new stream for another computation. Behavioral functions should be non-interfering and generally stateless; modifying the source during traversal is not ordinary collection editing.
Java example
31. How does Optional communicate absence, and how should callers consume it?
Optional<T> represents either one non-null value or an explicit absence. It is especially useful as a return type when “no result” is normal and callers must consider that possibility. An Optional variable itself should not be null; return Optional.empty() instead.
Consume it with transformations such as map and flatMap, a deliberate fallback, or orElseThrow when absence violates the caller's requirements. Unconditional get() merely moves a missing-value failure to a different exception. orElseGet computes its fallback only when empty, whereas the argument to orElse is evaluated before the call.
The example trims a nullable nickname, treats blank text as absent, and uppercases a present value. Optional is not an automatic replacement for every field or parameter; API clarity and the distinction between absence and failure still matter.
Java example
32. How would you write a palindrome check with an explicit character-handling policy?
Define the character policy before implementing the comparison. This version accepts non-null ASCII text only, compares it exactly and case-sensitively, and treats spaces and punctuation as ordinary characters. Empty and one-character strings are palindromes. Non-ASCII input is rejected rather than silently mishandled as independent UTF-16 code units.
After validating the input, two indices move inward. Any unequal pair returns false; reaching the center returns true. Validation happens first, so an early mismatch cannot conceal an invalid character elsewhere in the string. Time is O(n) and auxiliary space is O(1).
Thus level and the empty string are true, while Level is false. A Unicode-aware requirement needs a separate policy for code points, normalization, case folding, and possibly grapheme clusters; this deliberately narrow function makes none of those claims.
Java example
33. How would you count word frequencies using a Map?
For already-tokenized input, use each word as a map key and merge a count of one. This version accepts a non-null list of non-null, nonempty tokens, compares tokens exactly and case-sensitively, and performs no punctuation stripping or language-specific tokenization. Tokenization belongs to the caller's explicitly chosen policy.
merge(word, 1L, Long::sum) inserts one for a new key and adds one for an existing key. A HashMap does not promise iteration order, so the example sorts only for display, not for counting. Empty input returns an empty map.
For n tokens and u distinct tokens, expected map work is O(n), with O(u) entries, assuming suitable hash distribution and bounded-cost keys. With arbitrary string lengths, hashing and equality costs also depend on the characters examined. The input list is unchanged.
Java example
34. How does an enum improve a model compared with unrelated integer constants?
An enum defines a closed set of named values with its own type. A method accepting Status cannot accidentally receive an unrelated integer such as a retry count. Enum constants are instances, so the enum can attach fields, constructors, and behavior rather than scattering parallel integer-to-label mappings around the program.
For example, PENDING, APPROVED, and REJECTED can each carry an explicit external code. Compare enum values with ==; each named constant has a unique identity within its runtime enum class. A null enum still needs deliberate handling when used in a switch or dereferenced.
Do not persist ordinal() as a stable business identifier: adding or reordering declarations changes positions. Use an explicitly maintained code when storage or network contracts must survive source evolution.
35. What does a record generate, and why is record immutability only shallow?
A record concisely declares a transparent data carrier. For its components, Java supplies private final fields, public accessors named after the components, a canonical constructor, and component-based equals, hashCode, and toString implementations unless explicitly provided where allowed. A record is implicitly final and cannot extend a user-selected superclass, but it can implement interfaces.
Its immutability is shallow: a final component reference can still point to a mutable list or array. The compact constructor below copies its list into an unmodifiable list, rejecting null lists and null elements. Changing the original list therefore does not change the record. This is sufficient here because String elements are immutable; a list of mutable elements would need a separate element-ownership policy. An array component would also need defensive handling.
Java example
36. How do byte streams, character readers, and character encodings differ?
Byte streams such as InputStream and OutputStream handle raw bytes. They are appropriate for binary content such as images or compressed data. Character readers and writers handle text represented as characters; a bridge such as InputStreamReader decodes incoming bytes using a character encoding, and OutputStreamWriter encodes outgoing characters.
An encoding defines that conversion. The bytes for a character can differ between UTF-8 and another encoding, so decoding with the wrong one can corrupt text or report malformed input. Specify StandardCharsets.UTF_8 when that is the format's contract rather than relying on ambient defaults.
Java char represents a UTF-16 code unit, not necessarily a complete Unicode character. Even correctly decoded text may need code-point or grapheme-aware processing. Buffering changes I/O efficiency, not the distinction between bytes, encoding, and text.
37. How would you read a small UTF-8 text file and handle ownership of its resources?
For a small text file, Files.readString(path, UTF_8) reads and decodes the entire file and returns a String. It opens and closes its internal resource, so the caller has no returned reader to close. The checked IOException should be propagated or handled at a boundary that can report or recover from the failure; returning an empty string would confuse failure with a genuinely empty file.
The utility below rejects a null path and makes the encoding explicit. It preserves the decoded content, including line separators. Because the result is fully materialized, memory use grows with file size; it is not a suitable general solution for unbounded files. For incremental reading, use a reader in try-with-resources and close it in the same scope that owns it.
Java example
38. How do Instant, LocalDate, and ZonedDateTime represent different time concepts?
Instant represents a point on the timeline, suitable for recording when an event occurred and comparing timestamps across locations. It does not carry a human-facing regional time zone. LocalDate represents a calendar date without a time or zone, suitable for a birthday or invoice date; it cannot identify one moment by itself.
ZonedDateTime combines local date and time with a zone such as Europe/Paris and its resolved offset. Use it when regional calendar rules matter, such as an appointment presented in a user's zone. Converting a local time to a zone may encounter a daylight-saving gap or overlap, so a local date-time is not always a unique instant.
Choose the type from the domain meaning, not from formatting convenience. “Tomorrow at 09:00 locally” and “exactly 24 hours later” can differ across clock changes.
39. How do creating a Thread and submitting a task to an ExecutorService differ?
Creating a Thread couples one task to a thread whose start and lifetime the caller manages. Calling start() schedules execution on that new thread; calling run() directly is just a method call on the current thread. The caller can use join() to wait for completion.
An ExecutorService separates task submission from execution policy. Depending on its implementation, it can reuse worker threads or create threads per task. submit returns a Future that represents completion and can return a value or report failure; an executor also requires an explicit lifecycle policy.
This Java 21 example owns a single-worker executor in try-with-resources, so it is closed after use. get() waits for the result and exposes task failures through ExecutionException. Real applications also need suitable limits, cancellation, and timeouts when work can stall.
Java example
40. How would you test a small Java function using normal, boundary, and invalid inputs?
Start from the function's contract, then choose examples that exercise different obligations. For clamp, a valid range has minimum <= maximum; values below or above it map to the nearest endpoint, and interior values are unchanged. An inverted range is invalid and must throw IllegalArgumentException.
The tests below cover ordinary interior and exterior values, exact endpoints, a one-value range, integer extremes, and invalid bounds. They use explicit checks rather than Java's assert statement, which may be disabled unless assertions are enabled. The invalid-input test fails if no exception is thrown and accepts only the required exception type.
These are deterministic, bounded checks with no time or network dependency. They document important cases but do not prove every input correct; broader generated tests could additionally verify that every result stays within the requested range.
Java example
Java Interview Questions and Answers for Intermediate
The intermediate answers compare approaches through their contracts, ownership rules, and failure modes. They separate type safety from runtime behavior and explain when an apparently concise solution changes correctness or cost.
41. How do wildcard bounds express producer and consumer roles in a generic API?
Use ? extends T for a source that produces values assignable to T, and ? super T for a destination that accepts T values. This is PECS: producer extends, consumer super. Generic types themselves are invariant: List<Integer> is not a subtype of List<Number>.
An extends-bounded list can be read as T, but its unknown element type prevents adding arbitrary non-null T values. Adding null is type-correct, although the implementation may reject it. A super-bounded list accepts T, but its elements can only safely be read as Object. Wildcards do not imply immutability. This copy appends to a mutable destination and prints [1, 2]; it makes one traversal, excluding destination-operation costs.
Java example
42. How does type erasure affect overloads, runtime checks, and generic arrays?
Erasure replaces a type variable with its leftmost bound, or Object when unbounded, and removes type arguments from runtime type representations. Consequently, methods differing only by List<String> versus List<Integer> parameters have the same erased signature and cannot overload each other.
A runtime test against List<?> is allowed; testing an arbitrary Object against List<String> cannot verify its element type. Ordinary unbounded T is not reifiable, so new T[10] and new List<String>[10] are illegal. Prefer a collection or accept an array factory when an array is required.
The compiler can generate bridge methods to preserve overriding after erasure. Erasure does not remove every trace of generics: declared generic signatures can remain available through reflection, while individual collection objects do not retain enforced element-type arguments.
43. When should a method declare a type parameter instead of accepting an unbounded wildcard?
Declare a type parameter when the API must express a relationship between types, such as a collection's element type and the returned value. An unbounded wildcard is appropriate when the method only needs operations valid for an unknown element type, such as reading its size or treating elements as Object.
Here, first preserves the caller's element type without a cast, while sizeOf has no type relationship to express. The Optional result distinguishes an empty list from a present first element; this contract rejects a null first element rather than silently treating it as absent. The helper does not copy or modify the list. Indexed access cost depends on the list implementation, although index zero is inexpensive for common implementations.
Java example
44. How would you sort objects by multiple fields with a clear null policy?
Build the ordering from named field comparisons, then state separate policies for null objects and null field values. This comparator orders people by name, puts null names last, and breaks equal-name ties by ascending age. The outer wrapper puts null people last. thenComparingInt avoids subtraction, which can overflow and violate comparator ordering.
Comparator equality means compare(a, b) == 0; it need not match object equality. That distinction matters in TreeSet and TreeMap, which use ordering to identify equivalent elements or keys. The two fields cover all components of this record, but a larger domain object may require another tie-breaker. Sorting mutates this mutable list, performs O(n log n) comparisons, and retains input order among comparison-equal elements.
Java example
45. How do Arrays.asList, List.of, and List.copyOf differ in mutability and aliasing?
Arrays.asList(array) creates a fixed-size view backed by the array: set is supported and changes are visible in both directions, but adding or removing elements is unsupported. Null elements are allowed.
List.of creates an unmodifiable list and rejects null elements. List.copyOf(collection) creates an unmodifiable snapshot of the collection's elements and also rejects nulls; later structural changes to the source are not reflected. It may reuse a suitable unmodifiable list, so a distinct object identity is not promised.
All three retain element references rather than deeply copying objects. Unmodifiable does not mean that mutable elements become immutable. In the example, the backed view sees B, while the snapshot retains A; trying to add an element to either list would fail.
Java example
46. How should a collection be modified during iteration without relying on fail-fast behavior?
Use the iterator's own remove operation when its collection supports removal, or use removeIf for a predicate-based deletion. An iterator permits one removal after each successful next; calling it before next or twice for the same element is invalid. A list iterator additionally supports controlled replacement and insertion.
Do not structurally modify an ordinary list through the list itself inside an enhanced for loop. A ConcurrentModificationException is only a best-effort indication of misuse, not a guaranteed detector or a synchronization strategy. Concurrent access requires an appropriate collection or external coordination. This example deliberately uses a mutable ArrayList; factory-created unmodifiable lists do not support these operations. It preserves the order of the remaining elements.
Java example
47. How would you implement a bounded least-recently-used cache with LinkedHashMap?
An access-ordered LinkedHashMap maintains entries from least recently accessed to most recently accessed. Override removeEldestEntry to evict after insertion when the size exceeds a positive capacity. A successful get refreshes an entry's position, and inserting another entry can then evict the least-recently-used key.
Composition keeps callers from accessing operations that could violate the cache abstraction. This implementation rejects null keys and values so that a null result unambiguously means a miss. Standard lookup and insertion have expected constant-time costs under normal hashing assumptions, with O(capacity) retained entries. It is not thread-safe: even get changes access order. Concurrent callers need one shared lock around all operations, or a purpose-built concurrent cache with an explicit eviction policy.
Java example
48. How would you find the k largest integers without sorting the entire input?
Maintain a min-heap containing at most k values. Its root is the smallest retained candidate: a larger incoming value replaces it, while a smaller value cannot belong among the retained largest values. This version treats duplicates as separate occurrences and returns the result in descending order without changing the input.
The contract rejects k < 1; if k exceeds the input length, all values are returned. An empty input therefore produces an empty result. Let m = min(k, n). Heap processing takes O(n log(m + 1)) time and O(m) space, followed by O(m log m) output sorting. Iterating a PriorityQueue does not itself produce sorted output, so that final sorting step is deliberate.
Java example
49. How do map() and flatMap() differ for Stream and Optional?
Stream.map transforms each input element into one result; if the result is a stream or collection, that nesting remains. Stream.flatMap transforms each element into a stream and concatenates those streams into one pipeline. Neither operation requires mutating the original collections.
Optional.map similarly wraps a non-null mapping result, so mapping to an Optional produces nesting. Optional.flatMap accepts a function already returning an Optional and avoids that extra wrapper. For an empty optional, neither mapper runs. A null result from Optional.map becomes empty, whereas an Optional.flatMap mapper must return a non-null optional.
The example flattens two word lists, then unwraps a lookup result. Encounter order is retained here because the source lists and their streams are ordered.
Java example
50. When should a stream use reduce() rather than collect()?
Use reduce to combine values into one value with an associative operation and, when supplied, a valid identity. Integer addition with identity zero is a conventional example. Associativity lets the implementation regroup operations; floating-point addition can produce different rounding results when regrouped, so numerical requirements matter.
Use collect when accumulation builds a mutable container. Its supplier creates independent containers for partitions, and its combiner merges them. A mutable StringBuilder or ArrayList used as a shared reduce identity breaks those assumptions and can fail under parallel execution.
The example computes a scalar total and collects a separate list. Both traverse O(n) elements; the total requires constant accumulator space, while the list requires O(n) result space.
Java example
51. How would you group objects and compute a per-group total with collectors?
Combine groupingBy with a downstream summingLong collector instead of first building lists and then traversing every group again. The classifier chooses the group key, and the downstream collector keeps each group's running total. Here, amounts are integer cents, avoiding binary floating-point representation of currency fractions.
The supplied TreeMap makes result iteration deterministic by sorting region keys. With g groups and n orders, this implementation takes O(n log g) map work and O(g) accumulator space. A hash-based result would generally offer expected O(n) aggregation without a key-order guarantee. Null region keys are rejected by the record constructor. long addition can overflow; larger or untrusted totals require a checked accumulation policy or an arbitrary-precision representation.
Java example
52. How should Collectors.toMap handle duplicate keys?
The two-argument Collectors.toMap rejects duplicate mapped keys with IllegalStateException. If duplicates are valid, supply a merge function that expresses the business rule: add quantities, retain the highest score, or select a winner using an explicit ordering. Silently keeping the first value is only correct when first occurrence has defined meaning.
This example retains each key's maximum score. Integer::max is associative, so partitioned combination does not change that result. The LinkedHashMap supplier gives first-key encounter order for this sequential pipeline; the default collector does not promise a particular map implementation. Inputs here have non-null keys and values. If the requirement is to preserve every duplicate value rather than collapse them, use groupingBy to produce lists instead.
Java example
53. Why must stream lambdas be non-interfering, and what makes a parallel stream safe or worthwhile?
A non-interfering stream lambda does not modify the stream's source while the pipeline executes. A stateless lambda also avoids depending on changing shared state. Violating these requirements can produce exceptions or inconsistent results even before parallel execution is considered. Thread-safe side effects are not automatically deterministic, ordered, or efficient.
A parallel pipeline is a good candidate when independent CPU work is substantial, the source splits efficiently, and reductions have associative operations with correct identities and combiners. Partitioning, scheduling, merging, and ordering constraints can outweigh the benefit for small or cheap workloads. Blocking I/O and contention need separate concurrency design.
Collect results through suitable collectors rather than appending to one shared ArrayList. Measure representative end-to-end performance against a sequential implementation; .parallel() is neither a correctness repair nor a guaranteed speedup.
54. How do primitive streams help avoid boxing in numeric pipelines?
IntStream, LongStream, and DoubleStream carry primitive values through numeric operations, avoiding the boxed representation required by Stream<Integer> and similar reference streams. Methods such as mapToInt and mapToLong switch into these pipelines; boxed switches back when an object collection is needed.
Primitive specialization does not change arithmetic limits. IntStream.sum returns int, so a large sum can overflow even when every individual element fits. Widen before addition, as shown, rather than casting an already-overflowed result afterward. A long sum can also overflow at a larger range. Unboxing null elements still throws an exception. summaryStatistics computes count, minimum, maximum, sum, and average in one traversal; its empty-input sentinel values require interpretation.
Java example
55. How do pattern matching for instanceof and switch simplify type-dependent logic in Java 21?
An instanceof type pattern combines a type test with a safely scoped variable, removing the repeated cast. The variable is usable only where flow analysis establishes that the match succeeded, such as the right side of &&. A null reference does not match a type pattern.
Java 21 also supports finalized pattern matching in switch, including guarded cases using when. Put specific cases before broader cases to avoid domination errors, and make switch expressions exhaustive. Null handling is explicit here: case null handles null, while an ordinary default alone would not prevent a null selector from throwing. These examples use stable Java 21 syntax and require no preview flags.
Java example
56. How would you model a closed family of outcomes using sealed types and records?
A sealed interface constrains its permitted direct implementations, while records make concise carriers for each outcome's data. Consumers can switch over the known alternatives without a catch-all branch, allowing the compiler to detect missing cases when the hierarchy changes and consumers are recompiled.
Direct implementing classes must be final, sealed, or non-sealed; records are implicitly final. Permitted direct subtypes must be in the same named module, or the same package when the sealed type is in an unnamed module. A non-sealed branch deliberately reopens extension, so the entire descendant tree is not necessarily closed.
The example treats null as invalid using requireNonNull. A successful zero count remains distinct from a failure, unlike an ambiguous numeric sentinel.
Java example
57. How do compact record constructors validate and defensively copy components?
A compact record constructor validates or normalizes the implicit constructor parameters before the compiler assigns them to the record fields. Reassigning a parameter is allowed; directly assigning the corresponding instance field in a compact constructor is not. Throwing an exception prevents creation of a record that violates its invariant.
Here, a blank owner is rejected, and List.copyOf prevents later structural changes through either the caller's list or the generated accessor. It also rejects a null list or null list elements. The copy is shallow: mutable element objects would still require their own copying or immutable representation. The example uses immutable strings, so returning the copied list is safe. A record's final component fields alone would not protect a caller-supplied mutable collection.
Java example
58. When are nested static classes, inner classes, and local classes appropriate?
A static nested class is useful when a helper belongs conceptually to an outer type but does not need a particular outer object. It has no implicit enclosing instance and can be created without constructing the outer class.
A non-static member inner class is tied to an enclosing instance and can access that instance's members. This is convenient for a tightly coupled view or adapter, but retaining the inner object can also retain the outer object and its reachable state.
A local class limits a named helper to a block, such as one method. Captured local variables must be final or effectively final; that restricts reassignment of the variable, not mutation of an object it references. Prefer the narrowest scope that communicates ownership and avoids accidental lifetime coupling.
59. How do default methods resolve conflicts between interfaces?
A concrete inherited superclass method takes precedence over an interface default method with the same signature. Among interface defaults, a more specific subinterface's override takes precedence over its ancestor's version. Two unrelated inherited defaults create a conflict that the implementing class must resolve explicitly.
The class can implement entirely new behavior or delegate to a selected direct superinterface using InterfaceName.super.method(). That qualified call is constrained by inheritance rules; it is not a general way to invoke any arbitrary ancestor default. In this example, both direct interfaces contribute the same method signature, so the override deliberately combines them. Defaults help interfaces evolve, but adding one can still introduce conflicts into existing multiple-interface hierarchies.
Java example
60. How do annotations and reflection support runtime behavior, and what limits access?
Annotations attach metadata; a framework or application must interpret that metadata to produce behavior. Runtime reflection sees annotations with RetentionPolicy.RUNTIME. The default retention is CLASS, which preserves metadata in class files but does not make it available through ordinary runtime annotation queries. @Target restricts valid annotation locations.
Reflection can inspect classes, methods, constructors, and fields, but invocation still involves access checks and argument validation. Java module boundaries restrict deep reflective access: setAccessible(true) is not an unconditional bypass, and trySetAccessible can return false. Open the intended package deliberately rather than assuming private members are universally accessible.
The example reads a method annotation without invoking the method or suppressing access checks. Annotation presence itself does not execute run.
Java example
61. How do package boundaries and Java modules differ in encapsulation?
Packages organize names and define package-private access. A public class in one package can normally be used from another when the surrounding module rules also permit it; package-private members remain limited to their package.
A named module adds an explicit dependency and encapsulation boundary through module-info.java. requires establishes readability of another module. exports exposes a package's public API to other modules, optionally only named recipients; it does not expose the package's private members. opens permits deep reflection into a package, optionally to selected modules, without making that package an ordinary compile-time API.
Exporting and opening are therefore different decisions. Module declarations improve dependency clarity and implementation hiding, but they are not a substitute for authorization checks on application operations or data.
62. How would you design and translate exceptions at a service boundary without losing the cause?
Translate an implementation-specific failure into a service-level exception when callers should depend on the service contract rather than the storage library. Preserve the original exception as the cause using a constructor that delegates to super(message, cause). A stable high-level message should avoid exposing credentials, file contents, or sensitive paths to clients.
Catch the specific failures being translated, not every Throwable; serious VM errors are not ordinary service outcomes. Choose checked or unchecked exceptions according to the recovery contract, not merely convenience, and avoid logging the same failure at every layer.
This example uses an unchecked service exception. Its temporary fixture deliberately requests a missing file and confirms that the IOException remains accessible through getCause; it is not a remote-service integration test.
Java example
63. How would you process a large text file without loading it all into memory?
Process lines incrementally using Files.lines or a buffered reader, and close the resource with try-with-resources. A terminal stream operation does not automatically close the file-backed stream. Specify the character encoding rather than relying on an external file's unstated format.
The example counts matching lines without collecting them. It takes O(file size) scanning time and retains only the I/O buffers, current line, and count—not the whole file. An exceptionally long individual line can still require substantial memory. Opening the stream can throw IOException; a later read failure during traversal is surfaced as UncheckedIOException. Avoid toList, sorted, or an unbounded grouping operation if bounded memory is the goal. The temporary file only demonstrates the method and is deleted afterward.
Java example
64. How would you make a time-dependent Java service deterministic in tests?
Inject a Clock instead of calling a global clock directly inside business logic. Production can supply Clock.systemUTC, while a test supplies Clock.fixed to hold time at an exact instant. This makes before, equal-to, and after-deadline cases reproducible without sleeping or depending on machine speed.
Define the boundary explicitly: this service considers a deadline expired when the current instant is equal to or later than it. Its fixed clock therefore produces true exactly at expiration and false one second beforehand. Use a deliberate zone when testing calendar dates, since the same instant can fall on different local dates. A clock models wall time; elapsed-duration measurements that must tolerate wall-clock adjustments require a monotonic timing source instead.
Java example
65. How do synchronized and ReentrantLock differ in capabilities and cleanup requirements?
Both synchronized and ReentrantLock provide reentrant mutual exclusion and memory-visibility guarantees when the same lock protects shared state. A synchronized block releases its monitor automatically on normal or exceptional exit, making it a strong default for simple critical sections.
ReentrantLock adds interruptible acquisition, timed or immediate tryLock, optional fairness, and multiple condition queues. These capabilities come with explicit cleanup: acquire the lock before entering try, and release it in finally. Unlock only after a successful acquisition. A fair lock can reduce throughput and does not guarantee fair thread scheduling.
The counter protects both its update and read with the same lock. Its sequential output demonstrates the API shape; correctness under contention comes from the locking contract, not from that single execution.
Java example
66. What does volatile guarantee, and why is volatile count++ not atomic?
A write to a volatile field happens-before a subsequent read of that field, providing visibility and ordering for the communicating threads. Volatile is useful for independently updated state such as a stop flag, but it does not make a sequence of operations indivisible.
count++ reads the value, calculates a new value, and writes it back. Two threads can read the same old value and lose an increment even when the field is volatile. AtomicInteger.incrementAndGet performs the increment atomically, while a lock can protect a larger invariant involving several fields.
This counter uses an atomic integer for updates. Its value can still overflow the integer range; atomicity does not provide arbitrary-precision arithmetic. Separate atomic fields also do not automatically form one atomic transaction.
Java example
67. How do Callable, Future, and CompletableFuture represent task results?
Callable<V> describes work that returns a value and can throw a checked exception. Submitting it to an ExecutorService returns a Future<V>, a handle for completion, result retrieval, and cancellation. Future.get can block and reports task failure through ExecutionException; a timed get bounds the caller's wait but does not automatically stop the task.
CompletableFuture<V> is both a future and a composable completion stage. It can be completed explicitly and linked to transformations, dependent asynchronous work, combinations, and recovery stages. get uses checked retrieval exceptions. join normally reports failure through unchecked CompletionException, but throws CancellationException directly for cancellation.
Cancellation is a request or state transition, not proof that underlying work stopped. In particular, cancelling a CompletableFuture does not interrupt its computation merely because mayInterruptIfRunning is true.
68. How do thenApply and thenCompose differ when composing CompletableFuture operations?
Use thenApply when a successful result is transformed into an ordinary value. Use thenCompose when that transformation starts another operation returning a completion stage; it flattens the result rather than producing a future of a future.
The completed futures below isolate this type distinction without pretending to perform network I/O. upper is a transformed value, while email follows the completion of the second stage. If an upstream stage fails, these success-only callbacks are skipped and the dependent stage completes exceptionally unless recovery is added.
Neither non-async method promises a new thread. For asynchronous variants, an explicit executor gives control over execution resources; the default async execution facility should not be assumed suitable for blocking service calls.
Java example
69. How would you size and bound an executor's work queue and choose a rejection policy?
Choose worker and queue limits from measured task duration, CPU versus waiting time, downstream capacity, memory per queued task, and acceptable queueing latency. A larger queue absorbs bursts but can hide overload and increase response time. With ThreadPoolExecutor, work queues after core workers are occupied; additional workers beyond the core are created only when queueing fails, up to the maximum.
A bounded queue makes overload visible. AbortPolicy throws RejectedExecutionException, allowing the caller to reject or retry under an explicit policy. CallerRunsPolicy can slow submitters, but risks blocking an event-loop or request thread. Silent discard policies require deliberate loss tolerance.
This one-worker, one-slot example deterministically fills capacity, observes rejection, then releases the worker. Java 21 try-with-resources closes the executor and waits for accepted work.
Java example
70. How should Java tasks cooperate with cancellation and interruption?
Interruption is a cooperative signal, not a forced thread kill. CPU-bound loops should check their interrupt status at sensible boundaries and stop cleanly. Blocking operations such as queue waits or sleeps may throw InterruptedException, generally clearing the status as they do so.
If the method's contract allows it, propagate InterruptedException so its caller can decide. If a boundary cannot propagate it, restore the status with Thread.currentThread().interrupt() and terminate or return an explicit cancellation result; do not restore it and blindly retry the same blocking operation forever. Release locks and close resources in finally or try-with-resources.
Future.cancel(true) and shutdownNow attempt interruption, but completion still depends on task cooperation and the blocking API. isInterrupted observes without clearing; Thread.interrupted observes and clears the current thread's status.
71. How does ConcurrentHashMap support atomic per-key updates without making multi-step workflows atomic?
ConcurrentHashMap makes operations such as compute, merge, and putIfAbsent atomic for the relevant key. Use them instead of a separate get followed by put, which can lose updates between threads. This example increments a per-key count with merge; Math.addExact rejects integer overflow rather than silently wrapping.
Keep remapping callbacks short and avoid blocking I/O or recursive map updates. A null remapping result removes the mapping, while null stored keys and values are forbidden. Thread-safe access to the map also does not make a mutable mapped object's own methods thread-safe.
Two atomic updates to different keys are not one transaction. Transfers or cross-key invariants need an additional coordination strategy followed by every participating operation, or a transactional data store.
Java example
72. How would you coordinate a bounded producer-consumer pipeline using BlockingQueue?
Use a bounded BlockingQueue to separate production from consumption and limit buffered work. put and take wait indefinitely, while timed offer and poll allow the caller to detect overload or stalled progress. Queue insertion also safely publishes preceding producer actions to a consumer retrieving that element.
This finite example has three known items, two worker threads, and a two-element buffer. It checks every timeout, propagates interruption through callable tasks, cancels unfinished work on exit, and closes the owned executor. A timeout means an operation did not finish in time; it is not proof that the producer has permanently finished.
For an open-ended pipeline, define completion explicitly—for example, one terminal marker per consumer after production ends—and coordinate producer failure, consumer failure, cancellation, and draining. BlockingQueue has no built-in close operation.
Java example
73. What are virtual threads in Java 21, and which workloads benefit from them?
Virtual threads are lightweight Java threads scheduled by the JVM onto carrier platform threads. Finalized in Java 21, they suit applications with many concurrent tasks spending substantial time waiting for supported blocking I/O. They improve scalable concurrency and throughput, not the execution speed of CPU-bound calculations.
Create one virtual thread per task rather than pooling virtual threads. Still limit scarce resources such as database connections and downstream request concurrency; cheap threads do not create unlimited service capacity. The example owns and closes a per-task executor and confirms that its task runs virtually.
Version matters: in Java 21, blocking while holding a synchronized monitor can pin the virtual thread to its carrier. Java 24 removed that monitor-pinning limitation, a change retained in Java 25; native/foreign-call scenarios can still pin. Do not generalize one release's limitations to all releases.
Java example
74. How do heap storage, JVM stacks, and metaspace differ?
The JVM heap is shared storage for class instances and arrays in the virtual machine's abstract model. JVM stacks are per-thread and contain frames for method invocations, including local variables, operand stacks, and execution bookkeeping. A local variable can hold a reference to an object; that does not mean the referenced object's lifetime is the stack frame's lifetime.
The JVM specification also defines a shared method area. HotSpot's metaspace is an implementation mechanism for class metadata, generally allocated from native memory rather than the Java object heap. It is not a third language-level category of ordinary variables.
Implementation optimizations can eliminate allocations or keep values in registers, so “every object physically occupies heap memory” is too absolute. Heap exhaustion, stack exhaustion, and metadata exhaustion also have different causes and limits.
75. What happens during class loading, linking, and initialization?
Loading creates a runtime class or interface representation from its binary form. Linking includes verification, preparation, and resolution; symbolic references may be resolved lazily. Preparation establishes static storage and default values before ordinary Java static initializers execute.
Initialization runs static field initializers and static blocks in textual order, with required superclass initialization occurring first. Active use, such as constructing an instance, invoking a static method, or reading a non-constant static field, can trigger it. Merely mentioning a type does not always initialize it.
A compile-time constant is an important exception: its value can be inlined into the caller. In this example, printing CONSTANT does not initialize Holder; accessing value does, so initializing appears between the two numeric outputs.
Java example
76. How do interpretation and JIT compilation affect performance and warm-up?
Java bytecode is a portable execution format, not a promise that every instruction is always interpreted. In a typical HotSpot configuration, interpretation and tiered JIT compilation cooperate: runtime profiling helps select frequently executed code for compilation and optimization. Inlining and specialization can improve steady-state execution, while invalidated assumptions can cause deoptimization and later recompilation.
Warm-up includes more than JIT activity: class loading, initialization, caches, and allocation behavior can all change early timings. There is no universal number of iterations after which every application is warm. JVM implementation, flags, hardware, and workload all matter.
Separate startup latency from steady-state throughput when evaluating performance, use representative inputs, and consume computed results so an optimizer cannot discard the measured work. One fast invocation is not reliable benchmark evidence.
77. What makes an object eligible for garbage collection, and why is collection timing nondeterministic?
For ordinary strong-reference graphs, an object becomes reclaimable when no path from live execution roots can reach it. Roots include references needed by running threads and reachable static state. Two otherwise unreachable objects referencing each other can still be collected; cycles do not require manual breaking just because they are cycles.
Eligibility is not a collection schedule. Collectors choose when to run, and soft, weak, or phantom references have additional processing rules. A local variable going out of lexical scope is not a precise lifetime boundary: an object can remain referenced elsewhere or become unnecessary before its enclosing block ends.
System.gc requests collection effort rather than guaranteeing reclamation or immediate execution. External resources must therefore be closed explicitly; garbage collection is not a deterministic file, socket, or lock-release mechanism.
78. How would you implement binary search with an unambiguous result contract?
Define the contract first: the input must already be sorted in ascending order, a present value returns any matching index, and an absent value returns -1. Duplicate values are allowed, but this method does not promise the first or last occurrence. The array is not modified, and null input is rejected.
Each comparison discards half of the remaining interval. Computing the midpoint as low + (high - low) / 2 avoids overflowing the sum of two valid indices. Runtime is O(log n), with O(1) auxiliary space; validating sortedness separately would cost O(n).
An empty array correctly skips the loop. This custom absence convention differs from Arrays.binarySearch, whose negative result encodes an insertion point; callers must not interchange the two contracts.
Java example
79. How would you merge two sorted integer arrays while retaining duplicates?
Keep one cursor in each ascending input array and repeatedly copy the smaller current value into a new result. On equality, copy from the left first, then retain the right occurrence for a later step; duplicates are never discarded. Once either input is exhausted, append the other input's remaining suffix.
The method accepts empty arrays, rejects null references, and leaves both inputs unchanged. Sortedness is a precondition, not something this implementation validates or repairs. It takes O(n + m) time and O(n + m) result space, with O(1) additional cursor storage.
Math.addExact detects overflow when computing the result length. Even a representable length can exceed the VM's allocation limit or available memory, so checked length arithmetic is not a guarantee that allocation succeeds.
Java example
80. How would you implement value equality for a class with array fields?
Arrays inherit identity-based equals and hashCode, so two distinct arrays with equal elements are not automatically value-equal. A class whose value includes an array should compare it with Arrays.equals and derive its hash with the matching Arrays.hashCode. Nested object-array structures may require the corresponding deep operations instead.
Defensive copies on construction and access keep the equality-relevant state stable. This is especially important when objects are hash-map keys. The example is final, making its instanceof equality check an exact-type comparison without subclass symmetry issues. Null arrays are rejected.
A record containing an array does not automatically gain element-wise array equality or defensive copying. Comparing arrays costs O(n) in the worst case, and computing this uncached hash also costs O(n).
Java example
Java Interview Questions and Answers for Experienced
The experienced answers connect design decisions to invariants, memory visibility, lifecycle, and measured workload behavior. They qualify release and implementation differences and avoid treating one successful run or a small timing result as a general proof.
81. How does the Java Memory Model use happens-before to make shared state visible?
Happens-before describes ordering and visibility guarantees, not elapsed time. Actions earlier in one thread happen-before its later actions. Unlocking a monitor happens-before a subsequent lock of that same monitor; a volatile write happens-before a subsequent read of that variable. Starting a thread publishes preceding actions to it, and successfully joining a terminated thread makes that thread's actions visible. These relationships compose transitively.
For example, writing ordinary fields and then publishing a volatile ready flag lets a reader that observes that publication see the preceding field writes. It does not make later unsynchronized mutations safe. Executor submission and successful Future.get() provide documented publication edges too. A missing edge permits problematic executions; it does not imply that every run must observe stale data. Visibility also does not make a compound operation such as count++ atomic.
82. How can immutable state be safely published, and what does final-field semantics not guarantee?
Construct the complete state without allowing this to escape, defensively copy mutable inputs, and publish the reference through class initialization, a volatile field, a lock, or a concurrent collection. That establishes a straightforward visibility argument for consumers.
Final-field semantics provide additional initialization safety: a reader that obtains a properly constructed object sees its initialized final fields, even without the usual publication synchronization. The guarantee also covers construction-time state reached through a final reference under the specification's rules. It does not guarantee that a racing reader will ever discover the reference, protect unrelated non-final fields, or make referenced objects immutable. A final list reference still permits list mutation unless ownership prevents it. Later writes to an array or collection require their own synchronization. Calling an overridable method or registering a listener from the constructor can expose the object before initialization is complete.
83. How would you design a thread-safe lazy singleton, and when is double-checked locking valid?
The initialization-on-demand holder idiom uses class initialization to create and safely publish one instance when get() first accesses the nested holder. It avoids explicit locks on the normal access path and keeps construction lazy. The singleton is scoped to the defining class loader, not necessarily the entire process.
Double-checked locking is valid when the shared instance field is volatile, the second null check occurs inside the initialization lock, and construction does not leak the object. Omitting volatile destroys the required publication argument. Neither technique makes the singleton's later mutable operations thread-safe. Constructor injection is often easier when tests need separate instances or configuration. The example prints true; initialization failure would not silently create a fresh instance on each later call.
Java example
84. How would you protect an invariant that spans multiple variables or map entries?
Choose a synchronization boundary that covers the whole invariant, including readers that need a consistent snapshot. Separate atomic fields or individually thread-safe map operations do not make a multi-field transaction atomic. Another option is one immutable state object replaced with a single compare-and-set operation, provided retries have no external side effects.
This ledger moves integer units between two balances under one private monitor. It validates the amount and computes the potentially overflowing destination balance before changing either field, so validation failure leaves the ledger unchanged. The snapshot uses the same monitor and cannot observe a half-completed transfer. Each operation uses constant auxiliary space and constant arithmetic work, excluding lock contention. The example prints Balances[left=60, right=40]. Real transfers spanning services or databases need an appropriate transaction protocol beyond this in-memory lock.
Java example
85. When should you use AtomicInteger, LongAdder, or a lock for shared counters?
Use AtomicInteger when a single integer needs atomic reads, updates, or compare-and-set decisions, such as reserving one of a bounded number of slots. Reading and then incrementing in separate calls is still a race; use an atomic update or a CAS loop for the combined decision. Functions supplied to retrying atomic updates must not contain non-repeatable side effects.
Use LongAdder for heavily updated statistics where a concurrent, non-atomic total is acceptable. Its striped state trades additional memory for reduced update contention. sum() is not an atomic snapshot while updates continue, so it is unsuitable for enforcing an exact admission limit. Use a lock when the counter participates in a larger invariant or requires a consistent snapshot with other fields. Integer overflow remains a domain concern with all three choices; atomicity does not imply checked arithmetic.
86. How would you prevent deadlock when an operation must acquire two account locks?
Require every operation that locks two accounts to acquire them in one global, stable order. Sorting by a mutable balance or ordinary hash code is unsafe: ordering can change or collide. Here the order key is immutable; distinct accounts with duplicate keys are rejected before locking. A central allocator could instead guarantee uniqueness.
The transfer takes the lower-key lock first and releases locks in reverse order using finally. Interruptible acquisition lets a waiting caller cancel without retaining the first lock. Amount validation and overflow checking happen before mutation. All other balance access must follow the same locking discipline; a method that reverses the order could reintroduce deadlock. Ordering prevents this lock cycle, not starvation or arbitrary deadlocks elsewhere. Work and extra storage are constant, excluding waiting. The example prints 7:3.
Java example
87. How do CompletableFuture timeouts, cancellation, and exception handlers affect underlying work?
orTimeout exceptionally completes the same CompletableFuture if its deadline wins; completeOnTimeout completes it with a fallback value. Neither inherently stops the supplier or its network request. get(timeout, unit) only bounds that caller's wait and does not complete the future. Cancelling a CompletableFuture changes its completion state; its mayInterruptIfRunning argument has no effect. Cancellation is not automatically propagated as a stop request to upstream work.
exceptionally computes a recovery value only after failure. handle transforms either success or failure. whenComplete observes both and normally preserves the original outcome, although an observer that throws can make an otherwise successful dependent stage fail. Non-async handlers may execute on a completing thread. Actual cancellation requires cooperation: retain a task handle where appropriate, use interruptible operations, configure I/O deadlines, and define ownership of resources that must be closed.
88. How would you limit downstream concurrency when using virtual-thread-per-task execution?
Keep virtual-thread-per-task execution, but place a semaphore around the scarce downstream operation. Four permits mean at most four permit-holding operations, regardless of how many virtual threads exist. Acquire before entering the protected work and release only after successful acquisition, using finally.
This bounded example submits eight tasks and uses timed permit acquisition and timed result waits. Its stand-in operation is finite and interruptible. A real client also needs connection/read deadlines; a future timeout alone cannot terminate uncooperative I/O. The semaphore limits active calls, not queued tasks or incoming request memory. A service still needs admission control or a bounded upstream queue. Pooling virtual threads just to enforce the downstream limit obscures that resource policy. Normal output is 8; no particular task order is promised.
Java example
89. Why do ThreadLocal usage and blocking code deserve a fresh review when migrating to virtual threads?
A thread-local cache sized for a small reusable worker pool can become one cache per request with virtual-thread-per-task execution. Large buffers, database connections, and expensive initialization can therefore multiply memory or resource use. Prefer explicit request context and shared resource pools where ownership permits; remove thread-local values in finally when their lifetime ends. Virtual threads support ThreadLocal, but support is not a recommendation to cache scarce resources in it.
Blocking behavior is JDK-sensitive. In Java 21, blocking inside synchronized can pin a virtual thread to its carrier, limiting scalability. JDK 24's monitor changes remove that monitor-related pinning; native/foreign interactions still require attention. Do not mechanically replace every monitor on a newer JDK. Review actual blocking paths, resource limits, library support, and measured workload behavior. Java 21 examples should not silently rely on later releases or preview context-propagation APIs.
90. How would you choose between a parallel stream, a bounded platform-thread executor, and virtual threads?
A parallel stream fits a sufficiently large, splittable data transformation with independent, mostly CPU-bound work and associative reductions. Parallel overhead, encounter-order requirements, and shared side effects can erase the benefit. Its API is not a general-purpose resource-isolation or admission-control mechanism.
A bounded platform-thread executor fits explicitly managed tasks when thread count, queue capacity, rejection, and lifecycle need direct control. Bound both workers and backlog: a fixed-size pool with an unbounded queue still permits unbounded pending work. Virtual-thread-per-task execution fits many tasks that spend substantial time waiting on supported blocking operations. It does not increase CPU capacity or database capacity. Apply downstream limits separately and review JDK-specific blocking behavior. Compare throughput, tail latency, memory, and overload behavior on representative workloads rather than declaring one option universally faster.
91. How would you design a cache that avoids duplicate loads without holding a global lock during I/O?
Store a future per key, installing it with putIfAbsent. The winner owns the load; other callers await its outcome. The winner performs I/O outside map callbacks and completes the placeholder. Failed loads complete waiting callers exceptionally and remove only that exact placeholder, allowing a later retry without deleting a replacement.
The example is synchronous for the winning caller and returns 3:3:1, showing one successful load reused twice. Waiters use interruptible get(), but the loader still needs its own I/O deadline. This minimal implementation requires a non-recursive loader; production code should detect and reject same-key recursion, which could wait on its own unfinished future. Keep shared futures private so one waiter cannot cancel everyone's result. This is a single-flight mechanism with an unbounded successful-result cache, not a complete production cache: add capacity, expiry, invalidation, and failure-retry policy. Space grows with retained keys.
Java example
92. How do equality, ordering, and mutability interact when objects are keys in hash-based or sorted maps?
Hash-based maps locate keys using hashing and equality. Fields used by equals and hashCode must remain stable while the key is stored; mutation can leave an entry in a bucket inconsistent with its current hash. Sorted maps instead use their comparator or natural ordering to identify equivalent keys. If comparison returns zero, TreeMap treats those keys as the same mapping even when equals returns false.
For example, BigDecimal("1.0") and BigDecimal("1.00") compare numerically equal but are not equal under equals, which includes scale. A hash map and a naturally ordered tree map can therefore have different entry counts. Choose canonicalization or an explicit comparator to match the domain, and document it. Copy mutable key components rather than assuming a record containing an array or mutable list automatically provides stable value-key behavior.
93. How would you expose a stable public generic API without leaking mutable implementation details?
Expose the narrow abstraction callers need, not an internal ArrayList or mutable map. Use ? extends T when reading values from a producer and ? super T when passing values to a consumer. Avoid wildcard return types when a concrete type parameter gives callers a simpler usable result.
A snapshot such as List.copyOf prevents structural mutation through the returned list and does not track later structural changes in the input. An unmodifiable wrapper is instead a view of its backing collection. Both remain shallow: mutable elements can still leak implementation state unless copied or represented immutably. Document null policy, ordering, ownership, and thread-safety. Before changing a published generic signature, check both source compatibility and erased binary signatures; a change that appears more flexible can still alter inference, overload resolution, or bridge-method expectations.
94. What are the tradeoffs of using records as public API or persistence models?
Records work well for transparent values whose public identity is their component list. They supply accessors and value-oriented methods, but immutability is shallow: a final component referencing a mutable list still exposes mutable state unless construction and access enforce ownership. Arrays also retain their usual reference-based equality unless the record explicitly supplies different semantics.
A public record commits clients to component names, types, canonical construction, and generated behavior. Adding or changing components can break constructor calls and binary clients, and may change equality or serialized representations. Validate invariants in the canonical or compact constructor and copy mutable inputs. Records are final and cannot extend a domain superclass. For persistence, verify the actual mapper's constructor and lifecycle requirements rather than assuming universal support or rejection. A separate persistence representation can isolate storage evolution from a stable public API.
95. How does evolving a sealed hierarchy affect exhaustive switch clients and binary compatibility?
An exhaustive switch over a sealed hierarchy encodes the permitted variants known when the client was compiled. Adding another permitted subtype may preserve binary compatibility under the language specification while still invalidating that client's exhaustiveness assumption. Recompiling the client can require another case. An old Java 21 exhaustive switch can throw MatchException if it receives an instance of the new variant that no compiled case handles.
Removing a permitted subtype is a different change: an existing class that is no longer permitted can fail linkage with IncompatibleClassChangeError. Treat hierarchy evolution as an API design decision, not merely a build change. A deliberate fallback case can provide domain-specific behavior for future variants, but also stops the compiler from forcing every client to handle newly added cases. Version producers and consumers together when unknown variants cannot be handled meaningfully.
96. How can a class-loader boundary make identically named classes different types?
A runtime class is identified by its binary name together with its defining class loader. Two plugin loaders can each define example.Customer; those classes have distinct identities even if their bytecode is identical. An object from one cannot be cast to the other's type. The loader that first requests a class is not necessarily the defining loader, because it may delegate loading.
Put shared interfaces and data contracts in a parent-visible loader and have plugins delegate those types rather than package isolated copies. Keep plugin-private implementations behind that shared boundary. JVM loading constraints help preserve consistent types across linked signatures; they do not merge independently defined classes. Also consider lifecycle: retaining a plugin class, instance, thread, or context loader can keep its loader reachable. Loader isolation is an architectural namespace mechanism, not a general security sandbox.
97. What do allocation rate, live-set size, pause goals, and throughput imply for garbage-collector selection?
Allocation rate controls how quickly new objects consume available space; the live set controls how much memory must remain reachable after collection. A high allocation rate with a small live set differs from a large, long-lived graph, even at the same heap size. CPU availability and heap headroom affect how much collection work can run concurrently without starving application threads.
Choose a collector against an explicit objective: throughput, pause distribution, footprint, or a combination. Java 21 G1 balances throughput with a soft pause-time goal; that goal is not a hard real-time guarantee. Concurrent low-pause collectors trade additional background work and headroom for shorter interruptions. Compare realistic load, startup, bursts, and steady state on the target hardware. Record tail latency, CPU, allocation, and live-set behavior before changing policy. There is no universal heap flag or collector that optimizes every workload.
98. How can object layout, boxing, and collection choice change the memory cost of an algorithm?
Two algorithms with the same asymptotic space bound can have very different memory costs. An int[] stores primitive values, while an ArrayList<Integer> stores references and may involve separate wrapper objects, unused backing-array capacity, and boxing during processing. Integer caching means not every boxed occurrence necessarily allocates a new wrapper, so object counts depend on values and construction paths.
Node-based structures add per-entry objects and references; flat arrays often improve locality but may require resizing or shifting. Views can avoid copying yet retain a much larger backing object. Exact headers, reference sizes, alignment, and optimization effects are VM- and configuration-dependent; the language specification does not promise a universal byte count. Compare the full retained graph, temporary allocation rate, and access pattern. Prefer primitive storage for dense numeric data when its API and mutation tradeoffs fit, then measure on the actual runtime.
99. How would you design a streaming aggregation that remains memory-bounded as input grows?
Streaming input prevents retaining every record, but does not automatically bound aggregation state. Counting every distinct key in a map takes space proportional to the number of unique keys. If that cardinality can grow with input, memory can still grow without limit.
For a fixed known key set, maintain a fixed-size accumulator and reject unknown keys. For unrestricted exact aggregation, partition to disk or external-sort bounded chunks, then merge sorted runs while aggregating adjacent equal keys. Bound partition skew, merge fan-in, record length, queues, and output buffering; spilling one oversized partition without a fallback is not a complete solution. Approximate sketches offer bounded state only by accepting a documented error model. Close Files.lines streams with try-with-resources, and do not collect the final output into an unbounded list. The memory budget must cover every stage, not just input traversal.
100. How would you implement a top-k frequency result with deterministic tie-breaking?
Count occurrences, then retain at most k entries in a heap whose head is the worst retained candidate. The desired order here is descending frequency, then ascending String natural order. Reversing that total comparator makes low-frequency or lexically later entries leave first. Finally sort the retained entries; heap iteration is not sorted.
Negative k is invalid, zero returns an empty result without scanning elements, and larger values return all distinct words. Null input and scanned null words are rejected. With n words and u distinct words, expected work is O(n + u log(k + 1)) for positive k, treating key operations as constant cost; string processing adds length-dependent costs. Space is O(u + min(k, u)). The example checks that the tie between a and b is deterministic and prints [Count[word=a, frequency=2], Count[word=b, frequency=2]].
Java example
101. How would you implement and test a stable deduplication method with a caller-supplied key extractor?
Define stability as retaining the first element for each key in encounter order. Keep a set of seen keys and append an element only when adding its extracted key succeeds. This leaves the input untouched and produces a structurally unmodifiable snapshot; it does not deep-copy retained elements.
The contract below rejects null inputs, extractors, elements, and extracted keys. Keys must have stable equality and hashing during the operation, and the extractor should be deterministic and free of mutations to the input. Expected time is O(n) and auxiliary space O(u) for u distinct keys, excluding extraction and hashing costs. Tests should cover empty input, all duplicates, no duplicates, collisions between unequal keys, order, null rejection, and input nonmutation. The runnable case deduplicates by string length, checks the first-wins result, and prints [a, bb].
Java example
102. How would you implement a bounded batch iterator without dropping or duplicating elements?
A batch iterator should consume each source element exactly once and only when next() requests a batch. Validate a positive batch size, make hasNext() delegate without consuming elements, and throw NoSuchElementException after exhaustion. The final batch may be shorter than the configured maximum.
Each returned list below owns its storage and is structurally unmodifiable; null elements are retained, and element objects are not copied. The wrapper does not support removal or concurrent use. Reading n elements takes O(n) work with O(batchSize) working storage, excluding batches the caller retains. The source must obey the iterator contract; a source exception can leave it partially consumed. Tests should cover empty input, one-element batches, exact multiples, a short final batch, repeated hasNext(), invalid size, and exhaustion. The example prints [1, 2], [3, 4], and [5].
Java example
103. How would you design an immutable aggregate containing mutable collections and byte arrays?
Immutability requires controlling the entire mutable object graph, not just declaring fields final. Copy the input list and each contained byte array, never expose those internal arrays, and return fresh copies when callers request mutable representations. If elements were themselves mutable objects, their relevant state would need equivalent ownership protection.
This final class keeps an unmodifiable list of privately owned arrays. Both construction and access perform a deep copy for this particular graph. Null lists and null elements are rejected. Copying costs O(m + b) time and space for m arrays containing b bytes; callers should account for that access cost. Inputs must not be concurrently mutated while the snapshot is being taken. The example mutates both the original array and an accessor result, then verifies that internal state remains unchanged and prints 1. A record would still need defensive construction and accessor logic.
Java example
104. How can dependency injection through constructors improve testability without a framework?
Constructor injection makes dependencies explicit and allows the object to validate them before use. Business logic depends on a small interface instead of constructing a network client, reading a global singleton, or consulting the system clock internally. Production wiring and test wiring can then supply different implementations without a framework.
The example injects a notifier and Clock. A fixed clock makes the exact expiry boundary deterministic, while a recording fake captures the observable effect. The policy is explicit: an instant equal to the expiry counts as expired. The test checks behavior and recorded output, not private implementation details, and prints [expired]. Additional cases should cover future expiry, earlier expiry, and notifier failure. Injection does not automatically make collaborators thread-safe or define their ownership; those contracts still belong in the API.
Java example
105. How would you test concurrent code without depending on arbitrary sleep durations?
Coordinate the event under test with latches or barriers rather than guessing how long another thread needs to run. Use bounded waits, retrieve worker results so their exceptions cannot disappear, and clean up the executor even when an assertion fails. The test should assert the shared-state invariant after a documented completion edge.
Here two workers announce readiness, wait for a common release, and each perform 1,000 atomic increments. Timed Future.get calls observe completion, and the expected result is 2,000. The gate creates an opportunity for overlap; it does not force every possible interleaving. A passing execution, repeated stress run, or sanitizer result cannot prove race freedom. That requires a synchronization argument against the memory model as well. This fixture uses finite work and bounded waits, no network access, and no timing-based assertion about which worker runs first.
Java example
106. How would you verify equals, hashCode, and Comparator contracts with generated and boundary cases?
Test relations, not just a few expected hash values. Equality needs reflexivity, symmetry, transitivity, consistency, and inequality with null; equal objects must have equal hashes. Unequal objects may legitimately collide. A comparator needs sign symmetry, transitivity, and consistent comparison against third values when two inputs compare as zero. Require consistency with equality only when the API promises it.
The bounded fixture checks an integer-key value model with a reproducible seed, duplicate values, and integer extremes. It uses Integer.compare, avoiding subtraction overflow, and prints contracts checked. A real model also needs domain boundaries: empty fields, Unicode variants, allowed nulls, subclass interactions, and mutation policy. Preserve failing seeds and minimize counterexamples. Generated tests explore examples; they do not prove universal correctness, and reproducibility should record the generator as well as its seed.
Java example
107. How would you measure a Java optimization without confusing JIT effects, dead-code elimination, or GC with speedup?
Start with a specific hypothesis and a representative workload, then verify that the optimized version produces the same required results. Use a benchmark harness such as OpenJDK JMH for a microbenchmark rather than treating one nanoTime loop as proof. Warmup, separate measurement iterations, and independent process forks help expose compilation and run-to-run effects.
Ensure results are consumed, inputs are not compile-time constants, and setup work is separated only when the production workload excludes it. Avoid a giant manual loop that changes optimization opportunities. Measure allocation and GC alongside throughput or latency, and report variability, workload sizes, JDK build, hardware, heap, and collector. Do not force GC between operations and assume that models production. Finally validate the change at application level: a faster isolated operation can lose overall through extra allocation, contention, startup cost, or a different input distribution.
108. How should a Java API distinguish invalid input, absent data, and operational failure?
Invalid input means the caller violated a documented precondition: reject it promptly with a suitable exception, such as IllegalArgumentException for an invalid range or NullPointerException for a required null argument. Absence is an expected outcome, such as no record matching an identifier; Optional<T> can express that in a return type without returning null.
Operational failure is different: a timed-out lookup is not evidence that the record does not exist. Preserve it as an exception with a useful cause, or an explicit result type when callers must handle named failure states. Choose checked versus unchecked exceptions according to the API's recovery and compatibility needs, not a universal rule. Document whether empty collections mean successful zero results, whether partial results are possible, and which failures are retryable. Never erase failures by indiscriminately converting them to Optional.empty().
109. How would you preserve numeric correctness when calculating money or other decimal quantities?
Represent decimal quantities with BigDecimal built from decimal strings or another exact representation. new BigDecimal(0.1) captures the binary floating-point approximation rather than the intended decimal text. BigDecimal.valueOf(double) uses the double's string representation, but cannot restore precision already lost in earlier floating-point calculations.
Define units, permitted scale, rounding mode, and the stage at which rounding happens. The example's explicit policy rounds a combined three-item total once to two decimal places using HALF_EVEN, producing 3.02; rounding each item first would produce 3.00. Neither policy is universally correct. Division may require an explicit rounding policy when the exact decimal expansion is non-terminating. Use compareTo for numeric equality when scale should not matter; equals also compares scale. If storing integer minor units instead, use checked arithmetic and a documented conversion rule.
Java example
110. How would you handle Unicode text when char-by-char processing is not sufficient?
A Java char is a UTF-16 code unit, so a supplementary Unicode character occupies two chars. Iterate code points with codePoints() or codePointAt plus Character.charCount when the algorithm concerns Unicode scalar characters rather than code units. Reconstruct output with appendCodePoint to avoid splitting valid surrogate pairs.
The example reverses code-point order and prints B😀A; it takes linear time and linear extra space. It deliberately does not claim to reverse user-perceived characters correctly: combining marks and emoji sequences can span multiple code points. For cursor movement or display-oriented segmentation, use character-boundary analysis such as Java 21 BreakIterator, whose default implementation supports extended grapheme clusters. Define normalization and locale-sensitive comparison separately. Also decide whether malformed UTF-16 containing unpaired surrogates is rejected or preserved; code-point traversal alone is not strict Unicode validation.
Java example
111. How would you separate elapsed-time measurement from wall-clock and calendar calculations?
Use System.nanoTime() differences for elapsed time within one JVM. Its origin is arbitrary, so a reading is not an epoch timestamp and should not be stored as a business event time. Compare elapsed differences rather than adding an unchecked deadline to a reading; account for the documented finite range of meaningful differences.
Use Instant with an injected Clock for timestamps and testable wall-clock decisions. Wall clocks can be adjusted, so subtracting two wall-clock readings is not a substitute for a monotonic timeout measurement. For calendar requirements, supply a time zone and distinguish date-based operations from fixed durations. Across daylight-saving changes, advancing a zoned time by one calendar day need not equal adding 24 elapsed hours. Define how gaps and overlapping local times are resolved. Keep timestamps, deadlines, durations, and calendar dates as separate concepts in the API.
112. How do Path resolution, normalization, and filesystem checks differ when handling a user-provided filename?
resolve combines paths, while normalize removes redundant lexical elements such as . and reducible ..; neither operation proves what filesystem object will be opened. The example rejects absolute paths and lexical escapes from an absolute normalized root. It uses Path.startsWith, not a string-prefix comparison, and prints report.csv without touching the filesystem.
This is only lexical containment. A symlink inside the root can point outside it, and an attacker may change filesystem entries between a check and an open. toRealPath resolves an existing path, but a later operation can still race with changes. Security-sensitive code needs an appropriate trusted-directory design, permissions, and possibly directory-relative operations such as SecureDirectoryStream where supported. Define policy for symlinks, new files, and provider-specific paths explicitly; a successful Files.exists check is neither authorization nor an atomic open.
Java example
113. How should an API transfer ownership of streams, executors, or other AutoCloseable resources?
Specify ownership at the API boundary. A method borrowing an input stream normally leaves it open for the caller; a factory returning an owned resource makes the caller responsible for closing it. A callback-based API can retain ownership and guarantee cleanup before returning. Document wrapper behavior because closing a wrapper may close the underlying resource.
Use try-with-resources for owned resources: it closes them in reverse declaration order and preserves a primary failure while attaching close failures as suppressed exceptions. AutoCloseable alone does not promise idempotent close. A Files.lines result owns an open file and must be closed even after short-circuiting. Executors need additional lifecycle clarity: shutdown() rejects new tasks but lets submitted work proceed; shutdownNow() only attempts interruption. Java 21 ExecutorService.close() waits for termination and is not a bounded-time shutdown policy. A component borrowing a shared executor should not close it.
114. What risks come with native Java serialization, and when should a versioned data format be preferred?
Native Java serialization reconstructs object graphs and can invoke class-specific deserialization behavior. With untrusted input, that creates risks beyond malformed data, including dangerous behavior in available classes and resource exhaustion. Prefer not to deserialize untrusted native object streams at all.
Where an existing trusted protocol requires serialization, define an explicit allow-list and graph limits, maintain dependencies, and validate domain invariants after reconstruction. Serialization filters can restrict classes, array lengths, graph depth, reference count, and bytes consumed, but are not enabled by default merely because the JDK supports them. A filter is defense in depth, not a blanket guarantee that accepted objects are safe.
A versioned data format is usually easier to evolve across services, languages, and long retention periods: define fields, schema versions, size limits, and compatibility rules independently of Java implementation classes. Alternative formats still require safe parsing and input validation.
115. When would ServiceLoader be preferable to hard-coded construction or reflective class names?
Use ServiceLoader when implementations should be discovered from deployment configuration while consumers depend only on a stable service interface. It avoids embedding provider class names in application logic. Keep provider selection explicit when several implementations are present, and define behavior for no provider or a configuration error; discovery order is not a priority policy.
For this classpath example, place a UTF-8 resource named META-INF/services/Ex115$Greeting on the runtime classpath containing the line Ex115$Hello. The public static nested provider has a public no-argument constructor. With that resource, output is hello; without it, output is no provider. Named modules use uses in the consumer and provides ... with ... in the provider instead. Service loading supplies discovery and lazy instantiation, not dependency injection, lifecycle management, or a security sandbox for untrusted plugins.
Java example
116. How do dynamic proxies differ from subclass-based interception in their method coverage?
JDK dynamic proxies implement a specified set of interfaces and dispatch calls through an InvocationHandler; they do not subclass the concrete target class. Methods available only on the implementation class are therefore outside that interface proxy's coverage. Calls to equals, hashCode, and toString also reach the handler and need deliberate semantics.
Interface default methods are not automatically executed as their default implementation by an arbitrary handler. Java 21 offers InvocationHandler.invokeDefault when that behavior is intended. Subclass-based interception instead relies on overriding eligible instance methods, so final methods, private methods, static methods, and final classes impose limits. Self-invocation behavior depends on the interception design and cannot be generalized across libraries. If a handler delegates through Method.invoke, account for InvocationTargetException wrapping and the interface's declared checked exceptions rather than accidentally exposing a different exception contract.
117. How would you make a collection-processing API explicit about ordering, nulls, duplicates, and parallelism?
State these choices as observable guarantees rather than leaving them to the current collection implementation. For example, a deduplication API could publish this contract:
Concern | Chosen contract |
|---|---|
Order | Preserve first encounter order |
Nulls | Reject null input, elements, and keys |
Duplicates | Keep the first element per equal key |
Ownership | Return an unmodifiable shallow snapshot |
Execution | Sequential; callbacks run on the calling thread |
For input [a, bb, c] keyed by length, the result is [a, bb]. A parallel implementation cannot silently change which representative wins or introduce concurrent callback execution if clients rely on this contract. Java 21 sequenced collections express encounter order, but reversed() generally returns a reverse-ordered view, not an independent snapshot. Mutation visibility and element ownership still require documentation. Distinguish deterministic result order from the order or thread in which intermediate work happens.
118. How would you design a retry loop with bounded attempts, backoff, and cancellation?
Retry only failures classified as transient, and only when repeating the operation is safe or protected by an idempotency mechanism. Cap attempts, delay growth, and total elapsed time; add randomized jitter in a distributed deployment to reduce synchronized retry bursts. A timeout from one attempt must not leave uncontrolled overlapping attempts behind.
The example retries only its explicit TransientFailure, doubles a positive delay up to a cap without overflow, and propagates interruption. The sleeper is injected so the fixture records delays without waiting; it prints ok [10, 20]. Cancellation is checked before every attempt. The operation itself must cooperate with interruption and enforce its own I/O deadline: a bounded attempt count cannot bound a single hung call. Production code should also apply an overall deadline and preserve attempt diagnostics. It never catches Error or broadly retries every exception.
Java example
119. How would you evolve a library while preserving source, binary, and behavioral compatibility?
Source compatibility means existing client source still compiles; binary compatibility means existing compiled clients still link under the relevant rules; behavioral compatibility means documented observable behavior remains acceptable. These are different promises. Adding an overload can preserve old binaries yet make a source call with null ambiguous on recompilation. Adding an interface default method can create inherited-method conflicts in some client hierarchies.
Prefer additive changes with explicit migration paths, retain deprecated entry points when feasible, and avoid exposing mutable representations or implementation-specific types that constrain later changes. Review exception behavior, null handling, ordering, concurrency, serialization, and performance expectations as well as signatures. Run both unchanged precompiled clients and freshly compiled clients against the new library. Contract tests and representative integrations complement binary checks; a successful link alone does not establish behavioral compatibility. Publish versioning and removal policies before users depend on accidental behavior.
120. How would you review a Java 21 solution before adopting a newer supported JDK release?
Separate moving the runtime from adopting new language or library features. First inventory dependencies, agents, build plugins, native integrations, reflective access, module flags, and removed or deprecated APIs. Compile Java 21-targeted source with --release 21 when that remains the compatibility promise; this checks the supported language/API surface, not every behavioral difference on a newer VM.
Run the same correctness, integration, concurrency, and representative performance tests on the actual target build. Review garbage collection, startup, memory, locale/time-zone data, and version-sensitive virtual-thread behavior. Keep preview features explicitly opt-in and outside a stable baseline unless the project deliberately accepts their migration cost. In October 2026, Oracle designates Java 25 as a newer LTS than Java 21; that is not a claim that 25 is the newest release or that every vendor has identical support terms. Verify the selected distribution's policy and retain a rollback path.
Java Documentation and Further Reading
Code examples use Java 21 unless a different release is explicitly stated; Java 21 is an editorial and test baseline, not a claim that it is the newest Java release. Preview and incubating features are not assumed enabled, and newer APIs or changed runtime behavior must be qualified by release. Java language rules, Java SE API contracts, and JVM implementation choices are distinct. Focused snippets need their stated imports, enclosing declarations, inputs, and resource ownership. Any reported local compilation or execution applies only to the specified fixture and toolchain; it does not establish all thread interleavings, performance, external-service behavior, or production compatibility. Check the actual JDK distribution, build configuration, dependencies, and deployment constraints, and use representative tests or benchmarks before drawing broader conclusions.
Use these curated primary Java references to verify language rules, API contracts, concurrency guarantees, and JVM behavior. Select the documentation for the intended release, distinguish standard contracts from implementation details, and check whether a feature is final, preview, or incubating.
Similar Posts
