Java
Java is still the default language of enterprise backends, so its interviews range from language mechanics to JVM behavior under load. This tree covers the whole ladder: the object model, generics, collections, exceptions, concurrency, the memory model and garbage collection, I/O, and the modern language features added since Java 8.
on this pageshowhide
guide
overview
~2 minJava interviews run the whole ladder, from what `==` compares on two strings to why a service stalls under load. Junior rounds test the language itself: primitive and reference types, how the object model picks which method runs, what the `Object` contracts demand of your classes, and how the collections you use every day behave. Middle rounds shift toward library fluency and judgment — designing generic APIs rather than only calling them, deciding which failures deserve a checked exception, writing stream pipelines that are correct as well as short. Senior and principal rounds spend most of their time on concurrency and runtime behaviour: visibility between threads, choosing and sizing executors, virtual threads, leaks in a garbage-collected heap, and whether you measure before you optimise. At every level interviewers listen for whether your picture of the language stopped at Java 8. The hub follows those seams. The base layer is [Language Fundamentals](/topics/lang-java-fundamentals) and [Core Language Features](/topics/lang-java-core-language) — types, operators, strings, static members and initialization order. The object model is [Object-Oriented Programming](/topics/lang-java-oop), with [Best Practices & Design](/topics/lang-java-design) as its judgment layer. The type-safe library core is [Generics](/topics/lang-java-generics), the [Collections Framework](/topics/lang-java-collections) and [Exception Handling](/topics/lang-java-exceptions). [Functional Programming](/topics/lang-java-functional) covers lambdas, streams and `Optional`. The runtime and senior layer is [Concurrency & Multithreading](/topics/lang-java-concurrency), [Memory APIs & Diagnostics](/topics/lang-java-jvm-memory) and [Performance & Optimization](/topics/lang-java-performance). The platform surface is [I/O & NIO](/topics/lang-java-io-nio), the [Standard Library](/topics/lang-java-stdlib), [Security](/topics/lang-java-security) and [Modern Platform Additions](/topics/lang-java-modern), and the day-one toolchain is [Testing](/topics/lang-java-testing). Learn it roughly in that order. Fundamentals and core language features first, because the puzzle questions that open many rounds — overflow, string identity, initialization order — live there. The object model next, then collections, generics and exceptions, since almost every later answer is written in them. Take functional programming once interfaces and generics feel routine: a lambda is an instance of an interface, and stream signatures are generics at their densest. Leave concurrency until the rest is solid, then give it the most time; above junior level it is the most heavily weighted area of the hub. Memory, performance, security and the newer APIs matter most when the role names them — an on-call backend team, a latency-sensitive service, a platform that handles credentials.
primer
### Two kinds of value, one passing rule A Java variable holds either a primitive value or an object reference, and the difference explains a large share of junior puzzles. `==` compares what the variable holds, so on references it asks about identity; content comparison is a method the class has to supply. Boxing converts between the two worlds implicitly, which is where the surprises about cached wrappers and unboxing a `null` come from. Arguments are always passed by value — for an object, the value copied is the reference — so a method can change the object it receives but never rebind the caller's variable. ### The Object contracts hold the library together `equals`, `hashCode`, `compareTo` and `toString` look like conveniences, yet hash-based and sorted collections trust them without checking. Break the pairing between equality and hashing, or let a key's fields change after insertion, and the collection keeps running while silently losing entries. That is why interviewers return to these contracts from OOP, design and collections alike, and why immutable value types — records included — are the safe default for keys. ### Dispatch has two moments Which method runs is decided twice. The compiler picks a signature from the static types of the arguments, which settles overloading; the runtime then picks the implementation from the object's actual class, which settles overriding. Fields, static methods and private methods take part only in the first step. Much of the OOP section — inheritance, interfaces with default methods, abstract classes, nested classes — is this rule applied to a new case. ### Generics are a compile-time contract Type parameters are checked by the compiler and then erased, so the running program knows far less about `List<String>` than the source does. Erasure explains the restrictions: no `new T()`, no generic arrays, no overloads that differ only in type arguments. Wildcards exist because generic types are invariant; the question an interviewer is really asking is whether you know which way data flows through a parameter. ### Failure is part of the signature Checked exceptions make some failures a compile-time obligation for callers; unchecked ones signal bugs or conditions the caller cannot sensibly handle. The debate over where to draw that line is a design question, not trivia. The mechanics interviewers expect you to have cold are `finally` ordering, try-with-resources with suppressed exceptions, and never discarding a cause when wrapping. ### Shared mutable state needs a happens-before edge Without synchronization, one thread may never see another thread's write, or may see writes in an order the source does not suggest. The Java Memory Model defines which actions guarantee visibility — lock release and acquire, `volatile` accesses, thread start and join, safe publication through `final` fields. Everything else in concurrency sits on top: explicit locks, atomics, concurrent collections, executors, `CompletableFuture`. Virtual threads change the cost of blocking but leave these rules in place. ### Managed memory still leaks The garbage collector reclaims only what is unreachable, not what is unused. A static cache, a listener never removed, a thread-local on a pooled thread or a class loader pinned by one stray reference keeps memory alive indefinitely. Senior rounds pose this as a production scenario, and the answer they want is a diagnosis path, not a list of collector names. ### Measure before you tune The JIT compiler rewrites hot code as it runs, inlining, eliminating dead code and specialising for the types it has seen. That makes naive timing unreliable and many "obvious" micro-optimisations pointless. Interviewers weigh the discipline — profile, benchmark with a proper harness, change one thing — as heavily as any specific trick. ### The language keeps moving Since 2017 the platform has shipped on a six-month cadence, and modelling code now looks different: records for data carriers, sealed hierarchies for closed sets of cases, pattern matching in `instanceof` and `switch`, `var` for locals, text blocks. Candidates who answer only in pre-8 idioms read as out of date, even when their answers are correct.
- Reference type
- Any class, interface, array or enum type; a variable of such a type holds a pointer to an object, or null, rather than the value itself.
- Autoboxing
- The compiler-inserted conversion between a primitive and its wrapper class, in either direction; hides an allocation one way and a possible NullPointerException the other.
- String pool
- The JVM's table of interned String instances; literals are placed there, so equal literals share one object while strings built at runtime usually do not.
- Static type
- The type the compiler knows for an expression from its declaration; it selects overloads and limits which members you may call.
- Dynamic dispatch
- Choosing an overriding method's implementation at runtime from the receiver object's actual class rather than from the declared type of the variable.
- Record
- A class declared by its components, for which the compiler generates a canonical constructor, accessors, equals, hashCode and toString; its fields are final.
- Sealed class
- A class or interface that lists its permitted direct subtypes, letting the compiler know every case and check a switch over them for exhaustiveness.
- Type erasure
- The compiler's removal of generic type arguments after type-checking; at runtime only the raw class remains, with casts inserted where the source relied on the argument.
- Bounded wildcard
- A type argument such as ? extends T or ? super T that widens which parameterized types a method accepts, trading some operations for flexibility.
- Checked exception
- An exception type outside the RuntimeException and Error branches; the compiler requires callers to catch it or declare it in a throws clause.
- Try-with-resources
- A try statement that declares AutoCloseable resources and closes them in reverse order when the block exits, attaching close failures as suppressed exceptions.
- Functional interface
- An interface with exactly one abstract method; lambdas and method references are instances of one, and the target type decides which.
- Stream pipeline
- A source, zero or more lazy intermediate operations and one terminal operation; nothing runs until the terminal operation pulls elements through.
- Happens-before
- The Java Memory Model's ordering relation; if one action happens-before another, its effects are guaranteed visible to the second, across threads.
- Volatile field
- A field whose reads and writes are visible across threads and not reordered around one another, without providing mutual exclusion or atomic compound updates.
- Executor service
- A pool abstraction that accepts tasks and runs them on managed threads, separating what to run from how many threads run it and when.
- Virtual thread
- A lightweight thread scheduled by the JVM onto a small set of carrier threads, cheap enough to create one per task, including blocking tasks.
- GC root
- A reference the collector treats as live by definition, such as a local variable on a thread stack or a static field; reachability is traced from these.
- JIT compilation
- The runtime compilation of frequently executed bytecode into optimised machine code, guided by profiling data gathered while the program runs.
- JPMS module
- A named unit, described by module-info.java, that declares which packages it exports and which modules it requires; enforced at compile time and runtime.
The sections stack. Fundamentals and core language features define values, operators and the few built-in types — strings and arrays — with their own rules. The object model builds on them: classes, constructors, dispatch and the `Object` contracts decide how user types behave. [Generics](/topics/lang-java-generics) and the [Collections Framework](/topics/lang-java-collections) are the first large consumers of that model; a `HashMap` is only as correct as the keys' `equals` and `hashCode`, and a `TreeSet` only as correct as their ordering. That is why [the Object contracts](/topics/lang-java-oop-object-contracts) and [equals and hashCode](/topics/lang-java-design-equals-hashcode) appear in two different sections — one states the rules, the other is about living with them in real classes. [Functional programming](/topics/lang-java-functional) is not a separate language inside Java. A lambda is an object implementing a functional interface, a method reference is the same thing with less text, and stream operations are generic methods whose wildcard-heavy signatures are the [Wildcards](/topics/lang-java-generics-wildcards) section in practice. [Concurrency](/topics/lang-java-concurrency) reuses all of it: tasks are lambdas, `CompletableFuture` stages are functional interfaces, concurrent collections honour the same interfaces as the ordinary ones, and immutability — records, `final` fields — is often the cheapest route to thread safety. The runtime ring explains behaviour the language hides. [Memory APIs & Diagnostics](/topics/lang-java-jvm-memory) covers what the collector can and cannot reclaim and how to find out why the heap grows; [Performance](/topics/lang-java-performance) covers what the JIT does to your code and how to measure it honestly. The platform ring — [I/O & NIO](/topics/lang-java-io-nio), the [Standard Library](/topics/lang-java-stdlib), [Security](/topics/lang-java-security) — applies the core to files, sockets, time, crypto and reflection, and [Testing](/topics/lang-java-testing) is where every earlier section gets exercised. A small example where several of these meet: ```java sealed interface Payment permits Card, Transfer {} record Card(String last4, long cents) implements Payment {} record Transfer(String iban, long cents) implements Payment {} static long fee(Payment p) { return switch (p) { case Card(var last4, long cents) -> cents / 50; case Transfer t -> 25; }; } Map<Boolean, Long> feesByKind = payments.stream() .collect(Collectors.partitioningBy(p -> p instanceof Card, Collectors.summingLong(p -> fee(p)))); ``` The sealed interface lets the `switch` cover every case with no `default`; the record pattern pulls components out of `Card` in one step; the records bring value-based equality, so they would also work as map keys; and the stream is two collectors composed from lambdas that the compiler types from the surrounding generic signatures. Add a third `Payment` and `fee` stops compiling until it handles it.
- Java Language Fundamentals →
Types, operators, conversions and control flow are assumed by every other section, and many opening puzzles about overflow or casting live here.
- Object-Oriented Programming →
Where interviewers spend the most time overall: constructors, dispatch, interfaces versus abstract classes, and the Object contracts behind collections and design questions.
- Collections Framework →
The most examined library area; choosing an implementation and knowing its internals needs the equality contracts from the previous step.
- Generics →
Read after collections, whose signatures give the rules a concrete home; erasure and wildcards then explain what the compiler allows and refuses.
- Functional Programming →
Lambdas, functional interfaces and streams are everyday Java now, and they rest on the interfaces and generics you just covered.
- Concurrency & Multithreading →
With the core solid, give the deepest section the most time: threads, the memory model, locks, executors, then virtual threads.
Comparing strings or boxed numbers with
==because it worked in a quick test: small cached values and literals hide the identity check until production data arrives.Overriding
equalswithouthashCode, or using mutable fields in both: hash collections then lose entries silently instead of failing loudly — see Object Contracts.Saying Java passes objects by reference: it passes references by value, and interviewers probe exactly the case where the difference shows.
Expecting an overload to be chosen by the argument's runtime class: overloads are resolved from static types at compile time; only overriding dispatches on the actual object.
Answering a generics question as if type arguments exist at runtime: after erasure there is no
List<String>to check against, onlyList.Catching
Exceptionand logging it, or wrapping it without the cause: the stack trace that explains the failure is gone when someone needs it.Using a stream for its side effects, or reusing one after its terminal operation: pipelines are single-use and lazy, and side effects in lambdas can break under parallelism.
Treating
volatileas a lock: it guarantees visibility and ordering, but a read-modify-write such as an increment still races.Blocking on
get()orjoin()inside aCompletableFuturechain: it gives up the asynchrony the chain exists for and can exhaust the pool it runs on.Assuming the garbage collector prevents leaks: anything still reachable, like an unbounded static cache or a forgotten listener, stays in the heap for good.
Quoting micro-optimisations without a measurement: the JIT often already does them, and interviewers read unmeasured tuning claims as a red flag, not expertise.
This guide assumes Java 21, a long-term-support release; answers read the same on Java 25, the LTS that followed it. Feature releases have shipped every six months since Java 9 in 2017, with an LTS every two years from 17 on. The milestones interviewers still ask about: - **8** (LTS) — lambdas, method references, streams, `Optional`, default methods and `java.time`. The line between "old" and "modern" Java in most interviews. - **9** — the module system and JShell. - **10** — `var` for local variables. - **11** (LTS) — the standard HTTP client, new `String` methods such as `strip` and `isBlank`, and running a single source file directly. - **14** — switch expressions became standard; helpful NullPointerException messages arrived, and became the default in 15. - **16** — records and pattern matching for `instanceof` became standard. - **17** (LTS) — sealed classes; the SecurityManager was deprecated for removal, and it was permanently disabled in 24. - **21** (LTS) — virtual threads, pattern matching for `switch`, record patterns and sequenced collections. - **22** — the Foreign Function & Memory API became final. The Vector API is still incubating. The change that most often separates a current answer from a dated one is the pattern match: ```java // before Java 16 if (shape instanceof Circle) { Circle c = (Circle) shape; return c.radius(); } // Java 16 onward if (shape instanceof Circle c) { return c.radius(); } ``` The check, the cast and the binding become one step, and the same idea later extended to `switch` and to records.
Java the language is stewarded by Oracle through the OpenJDK project, and several vendors ship OpenJDK builds; a candidate should know that "which JDK" is usually a distribution question, not a language one. Interviewers expect you to place Java in three settings. On the **backend**, most Java code runs inside a framework: Spring Boot above all, Jakarta EE (the successor to Java EE) in older enterprise estates, and lighter frameworks such as Quarkus and Micronaut where start-up time and memory matter. Persistence usually goes through JPA with Hibernate, builds through Maven or Gradle, and tests through JUnit and Mockito — the last two are this hub's [Testing](/topics/lang-java-testing) section. **Big-data and messaging infrastructure** is the second home: many widely deployed systems in that space are written in Java or run on the JVM. **Android** is the third, though new Android code is mostly written in Kotlin now. The comparisons that come up most are with the other JVM languages and with backend rivals. Kotlin and Scala compile to the same bytecode and call Java libraries directly; Kotlin's pitch is null safety and less ceremony, Scala's a richer type system and functional style. Outside the JVM, C# on .NET is the closest peer in shape and use, and Go competes for services where a small static binary and simple concurrency beat Java's larger runtime. A strong answer names what Java trades for its ecosystem and tooling: more ceremony, a heavier runtime and slower start-up than the leanest alternatives.
explore
- Object-Oriented Programming263 questions
- Java's OOP Model5 questions
- Classes & Objects20 questions
- Methods26 questions
- Constructors19 questions
- Encapsulation (Access Mechanics)10 questions
- Inheritance (Mechanics)19 questions
- Polymorphism (Dispatch & Binding)13 questions
- Abstraction (Abstract Classes & Interfaces)25 questions
- Composition & Aggregation9 questions
- Nested & Inner Classes14 questions
- Enums15 questions
- Records15 questions
- Sealed Classes8 questions
- Pattern Matching14 questions
- Object Methods & Contracts51 questions
- Best Practices & Design144 questions
- Design in Java5 questions
- Design Patterns in the JDK105 questions
- equals() & hashCode()5 questions
- Immutability10 questions
- Effective Java Idioms19 questions
- Java Memory APIs & Diagnostics48 questions
- Bridge: JVM Platform Internals6 questions
- Strong References4 questions
- Soft References4 questions
- Weak References & WeakHashMap5 questions
- Phantom References, ReferenceQueue & Cleaner5 questions
- Memory Leak Patterns5 questions
- ClassLoader Leaks5 questions
- OutOfMemoryError Variants5 questions
- StackOverflowError4 questions
- Heap Dumps & Profiling Tools5 questions
- Concurrency & Multithreading253 questions
- Thread Basics25 questions
- Synchronization15 questions
- Thread Coordination5 questions
- Concurrency Utilities (Locks & Synchronizers)24 questions
- Atomic Variables17 questions
- Executor Framework39 questions
- CompletableFuture35 questions
- Fork/Join Framework10 questions
- Concurrent Collections20 questions
- Thread Safety Concepts & Hazards25 questions
- Virtual Threads & Structured Concurrency29 questions
- Performance & Optimization94 questions
- Profiling & Benchmarking30 questions
- Optimization Techniques39 questions
- JDK Diagnostic Tools25 questions
- Functional Programming142 questions
- Functional Concepts in Java6 questions
- Lambdas13 questions
- Method References5 questions
- Functional Interfaces14 questions
- Streams API89 questions
- Optional15 questions
- Testing132 questions
- JUnit (Unit Testing)64 questions
- Mockito (Mocking)47 questions
- Assertion Libraries (AssertJ / Hamcrest)11 questions
- JaCoCo Coverage5 questions
- Security63 questions
- Secure Coding on the JVM (Concept Bridge)5 questions
- Cryptography (JCA/JCE)40 questions
- Serialization Security5 questions
- Access Control (Legacy)13 questions
- Java Language Fundamentals185 questions
- Syntax & Basic Constructs28 questions
- Data Types26 questions
- Variables24 questions
- Operators40 questions
- Type Conversion & Casting23 questions
- Control Flow44 questions
- Core Language Features109 questions
- Strings38 questions
- Arrays35 questions
- Packages and Imports16 questions
- Static Members10 questions
- Initialization10 questions
- Generics117 questions
- Generic Fundamentals15 questions
- Bounded Type Parameters16 questions
- Wildcards25 questions
- Type Erasure29 questions
- Generic Restrictions32 questions
- Collections Framework121 questions
- Collection Hierarchy & Interfaces5 questions
- List Implementations19 questions
- Set Implementations15 questions
- Map Implementations27 questions
- Queue & Deque10 questions
- Iterators & Traversal15 questions
- Ordering & Comparison5 questions
- Collections Utility & Factories10 questions
- Performance & Selection15 questions
- Exception Handling82 questions
- Exception Hierarchy10 questions
- Handling Exceptions20 questions
- Throwing and Declaring19 questions
- Custom Exceptions14 questions
- Best Practices19 questions
- I/O & NIO111 questions
- I/O Streams18 questions
- File Handling14 questions
- Serialization19 questions
- NIO & NIO.246 questions
- Console & Standard Streams14 questions
- Java Standard Library / APIs232 questions
- Date & Time API43 questions
- Math & Numbers29 questions
- Wrapper Classes5 questions
- Regular Expressions44 questions
- Reflection, MethodHandles & VarHandle34 questions
- Annotations & Processing22 questions
- Serialization10 questions
- Module System (JPMS)40 questions
- Utility Classes5 questions
- Modern / Recent Platform Additions40 questions
- JShell (REPL)5 questions
- HTTP Client (java.net.http)5 questions
- New String Methods (Java 11+)5 questions
- Single-File Source Execution5 questions
- Helpful NullPointerExceptions5 questions
- Sequenced Collections5 questions
- Foreign Function & Memory API5 questions
- Vector API5 questions
questions
2,136 · 16 sectionsHow do you declare an abstract method, and what obligations does it place on subclasses?
basics
~20 sAn abstract method is written with the abstract keyword and no body — just a signature ending in a semicolon. Any concrete (non-abstract) subclass must override it and supply a real body, or it won't compile.
What is an abstract class in Java, and what can it contain that a regular interface (historically) could not?
basics
~20 sAn abstract class is a class marked with the abstract keyword that you cannot create objects from directly. It can mix finished methods with unfinished (abstract) methods that subclasses must complete. It can also hold normal fields and constructors.
Java lets you make a field public, so why does encapsulation favor private fields with accessor methods?
basics
~20 sA private field hides the data and lets the class control how it's read or changed through methods. That means you can add validation, compute values, or change how the data is stored later without breaking code that uses the class.
What are the four access levels in Java and what does each one mean?
basics
~20 sJava has four access levels: public (everywhere), private (only inside the same class), protected (same package plus subclasses), and default — written by adding no keyword — which allows access only inside the same package.
What is the difference between upcasting and downcasting in Java, and which one is implicit?
basics
~20 sUpcasting treats an object as one of its parent types (Dog seen as Animal); it is automatic and always safe. Downcasting treats it back as the more specific child type (Animal back to Dog); it needs an explicit cast and can fail at runtime.
What problem does the Builder pattern solve, and why are telescoping constructors and the JavaBeans setter pattern poor alternatives for a class with many optional parameters?
basics
~20 sBuilder solves having too many constructor parameters. Telescoping constructors (one per combination) become unreadable and error-prone. JavaBeans setters allow building an object step by step but leave it mutable and possibly half-built. Builder gives readable, named, optional parameters and a finished immutable object.
Compare try-with-resources to the old try/finally close pattern. Why is try-with-resources strictly better for managing AutoCloseable resources?
basics
~20 stry-with-resources declares the resource in the try header and closes it automatically when the block ends, even on exception — less code and no forgetting. Old try/finally needs a manual close() in finally, is easy to get wrong with multiple resources, and can hide the real exception if close() also throws.
What is a raw type in Java, why should you avoid raw types, and what do you lose by using them?
basics
~20 sA raw type is a generic class used without its type parameter, like List instead of List<String>. Avoid them because you lose compile-time type checking, so wrong types slip in and blow up at runtime with a ClassCastException.
What is a static factory method in Java, and why might you prefer one over a public constructor?
basics
~20 sA static factory method is a static method that returns an instance of its class instead of using new directly. You prefer it because it can have a descriptive name, can reuse cached objects, and hides how the object is built.
What is the relationship between equals() and hashCode() in Java, and why must they be overridden together?
basics
~10 sIf two objects are equal by equals(), they must return the same hashCode(). So whenever you override equals(), you must also override hashCode(), or hash-based collections like HashMap and HashSet will misbehave.
What are the main runtime memory areas the JVM divides memory into, and which are shared across threads versus per-thread?
basics
~20 sThe JVM splits memory into the heap (where objects live, shared by all threads), the stacks (one per thread, holding method calls and local variables), and metaspace (class metadata). The heap is where garbage collection happens.
What is a heap dump, and what are the main ways to capture one from a running or crashing JVM?
basics
~20 sA heap dump is a snapshot of all objects in the JVM heap at one moment, saved to a file. You can trigger it on demand with jmap, or have the JVM write one automatically when it runs out of memory using the -XX:+HeapDumpOnOutOfMemoryError flag.
Java has a garbage collector, so how can a Java program still leak memory?
basics
~20 sThe garbage collector only frees objects nothing else points to. If your code keeps a reference to an object you no longer use, the collector cannot free it. The memory is still 'reachable', just wasted. That is a Java memory leak.
What is an OutOfMemoryError in Java, why is it an Error rather than an Exception, and should you catch it?
basics
~20 sOutOfMemoryError means the JVM ran out of memory and could not get more, so it can't keep running normally. It's an Error, not a regular Exception, because it signals a serious problem you usually can't recover from. Don't catch it to keep going; fix the root cause instead.
What is a SoftReference in Java, and when does the garbage collector clear one?
basics
~10 sA SoftReference is a special wrapper around an object that lets the garbage collector throw that object away, but only when the JVM is running low on memory. Until then, the object stays alive.
A teammate uses a `volatile int` and writes `count++` for a shared request counter, expecting it to be thread-safe. Is it? Explain and fix it.
basics
~10 sNo. volatile makes the value visible across threads but count++ is read-then-add-then-write, three steps, so two threads can both read the same number and lose an update. Fix it with an AtomicInteger and incrementAndGet().
What is a BlockingQueue and what problem does it solve compared to a regular queue?
basics
~20 sA BlockingQueue is a thread-safe queue where a thread that takes from an empty queue waits until an item arrives, and (if bounded) a thread that adds to a full queue waits until space frees up. It makes producer-consumer hand-off safe and simple.
What does thenCombine do on a CompletableFuture, and when would you use it?
basics
~10 sthenCombine waits for two independent CompletableFutures to both finish, then merges their two results into one new value using a function you supply.
How do you manually drive a CompletableFuture to completion, and what is the difference between complete(value) and completeExceptionally(throwable)?
basics
~20 sA CompletableFuture isn't always finished automatically — you can finish it yourself. complete(value) makes it succeed with that value; completeExceptionally(ex) makes it fail with that exception. Both return true only if your call was the one that completed it.
What are the main ways to create a CompletableFuture that runs a task asynchronously, and how do supplyAsync and runAsync differ?
basics
~10 sUse CompletableFuture.supplyAsync when the task returns a value, and runAsync when it returns nothing. supplyAsync takes a Supplier and gives a CompletableFuture<T>; runAsync takes a Runnable and gives a CompletableFuture<Void>.
What are autoboxing and unboxing in Java, and why can they hurt performance in hot code?
basics
~20 sAutoboxing converts a primitive (like int) into its wrapper object (Integer) automatically; unboxing does the reverse. Each box can allocate a new object, which costs memory and creates garbage. In tight loops that adds up and slows things down.
What is jcmd, and why is it considered the modern, recommended replacement for one-off tools like jmap and jstack?
basics
~20 sjcmd is a JDK command-line tool that sends diagnostic commands to a running JVM. Instead of separate tools, one tool can dump the heap, print threads, run GC, show flags, and more. It's safer and unified, so it replaces jmap and jstack.
What are jconsole and VisualVM, and when would you reach for each to monitor a running JVM?
basics
~20 sBoth are free GUI tools that ship with (or pair with) the JDK to watch a live Java program: heap memory, garbage collection, thread count and CPU. jconsole is the minimal built-in monitor; VisualVM does more, including CPU/memory profiling and dumps.
What is jmap, and what are its two most common uses for inspecting a running Java application's heap?
basics
~20 sjmap is a JDK command-line tool that inspects a running Java program's heap (its object memory). Its two main uses are printing a histogram of how many objects of each class exist, and dumping the whole heap to a file for offline analysis.
What is JMH, and why should you use it instead of hand-rolled timing with System.nanoTime() loops for Java microbenchmarks?
basics
~20 sJMH is the Java Microbenchmark Harness, an official tool for measuring how fast small pieces of Java code run. It's better than manual nanoTime loops because the JVM warms up and optimizes code over time, and JMH handles that warmup and the JIT effects so your numbers are trustworthy.
What are the four core functional interfaces in java.util.function, and what is the shape (inputs and output) of each?
basics
~10 sFunction<T,R> takes one value and returns another. Consumer<T> takes one value, returns nothing. Supplier<T> takes nothing, returns a value. Predicate<T> takes one value, returns a boolean.
What is mutable reduction in the Java Streams API, and how does collect() perform it?
basics
~20 sMutable reduction combines stream elements by adding them into one mutable container (like a List or StringBuilder) instead of creating a new value each step. collect() does this: it makes a container, then drops each element into it.
What is a downstream collector, and how do you use one to count or sum the elements within each group of a groupingBy?
basics
~20 sgroupingBy can take a second collector that runs on each group. So instead of getting lists, you can count items per group with Collectors.counting() or add them up with summingInt(). The result is a Map from key to the computed value.
What does Collectors.groupingBy do, and what is the shape of the result?
basics
~20 sgroupingBy takes a function that maps each element to a key. It returns a Map where each key points to a list of all the elements that produced that key, like sorting items into labeled buckets.
How do you collect a Stream into a List, and what is the difference between Collectors.toList(), Collectors.toUnmodifiableList(), and Stream.toList()?
basics
~10 sUse stream.collect(Collectors.toList()) to get a List. toUnmodifiableList() gives a List you cannot change (add/remove throws). Since Java 16, stream.toList() is a shorter way to get an unmodifiable list.
What is Mockito's ArgumentCaptor and what problem does it solve?
basics
~10 sArgumentCaptor catches the actual value passed to a mock's method so you can store it and check it afterward with normal assertions, instead of only checking that the method was called.
What are argument matchers in Mockito, and why would you use any() or eq() instead of passing a literal value when stubbing or verifying?
basics
~20 sArgument matchers like any() or eq() tell Mockito how to match the arguments of a call instead of comparing exact values. Use any() when the value doesn't matter and eq(x) when you need a specific value but other arguments use matchers.
What is JUnit 5's assertAll, and what problem does it solve compared to writing several separate assertions?
basics
~20 sassertAll runs a group of assertions together and reports every failure at once. With plain asserts, the test stops at the first failure, so you only see one problem. assertAll shows all of them in one run.
In JUnit 5's assertEquals, what is the argument order, and why does getting it wrong matter?
basics
~20 sThe order is assertEquals(expected, actual). The first value is what you expect, the second is what your code produced. Swapping them still passes or fails correctly, but the failure message reads backwards and confuses you.
What is AssertJ and how does its fluent assertThat(...) style differ from JUnit's assertEquals or Hamcrest's assertThat?
basics
~20 sAssertJ is a Java assertion library. You write assertThat(actual) then chain readable checks like .isEqualTo(expected) or .isNotNull(). It reads left-to-right (actual first) and gives clear failure messages, unlike assertEquals(expected, actual) where the argument order is easy to mix up.
How does Java prevent SQL injection, and why does string concatenation of SQL fail to do so?
basics
~20 sNever build SQL by gluing user input into the query text. Use PreparedStatement with ? placeholders (or JPA named parameters) and bind values separately, so input is treated as data, not as code the database runs.
When encrypting and decrypting with RSA in Java, which key do you init the Cipher with, and what is the role of ENCRYPT_MODE vs DECRYPT_MODE?
basics
~10 sTo encrypt, init the Cipher in ENCRYPT_MODE with the recipient's public key. To decrypt, init in DECRYPT_MODE with the matching private key. Public key locks, private key unlocks.
How do you create a Cipher for AES in Java, and what does the transformation string passed to Cipher.getInstance mean?
basics
~10 sYou call Cipher.getInstance with a transformation string like "AES/GCM/NoPadding". It has three parts: the algorithm (AES), the mode (how blocks are chained, e.g. GCM or CBC), and the padding (e.g. PKCS5Padding or NoPadding).
How do you generate a symmetric secret key in Java using KeyGenerator, and what does init() control?
basics
~10 sAsk KeyGenerator for an algorithm like AES, call init() with the key size (for example 256 bits), then generateKey(). It returns a SecretKey you use to encrypt and decrypt.
How do you compute a cryptographic hash in Java using the MessageDigest API? Walk through the getInstance / update / digest lifecycle.
basics
~10 sCall MessageDigest.getInstance("SHA-256") to get an engine, feed bytes with update(...), then call digest() to get the final hash as a byte[]. digest() finishes the computation and resets the engine for reuse.
What are the arithmetic operators in Java and what does each one do?
basics
~10 sJava has +, -, *, / and % for add, subtract, multiply, divide, and remainder. There are also unary + and - that keep or flip a number's sign.
What is the simple assignment operator (=) in Java, and what does an assignment expression evaluate to?
basics
~20 sThe = operator stores the value on its right into the variable on its left. An assignment is also an expression whose result is the value that was assigned, so you can write a = b = 5 and both become 5.
What are autoboxing and unboxing in Java, and when does the compiler insert them?
basics
~20 sAutoboxing is the automatic conversion of a primitive (like int) to its wrapper object (Integer). Unboxing is the reverse. The compiler inserts these conversions for you when a primitive is used where an object is expected, or vice versa.
What do Java's bitwise operators &, |, ^, and ~ do, and how do they differ from the logical operators && and ||?
basics
~20 s&, |, ^ compare two numbers bit by bit (AND, OR, XOR); ~ flips every bit. They work on whole numbers. && and || work on true/false, only look at the second value if needed, and give back true or false.
What is a block statement in Java, and what does it have to do with variable scope?
basics
~20 sA block is code wrapped in curly braces { }. It groups statements together. A variable you declare inside a block can only be used inside that block; once the block ends, the variable is gone.
What happens in Java when you access an array element with an index that is outside the array's valid range?
basics
~10 sJava checks every array access at runtime. If the index is below 0 or at/above the array's length, it throws an ArrayIndexOutOfBoundsException instead of reading wrong memory.
Why is a Java array fixed-length once created, and how do you handle a collection that needs to grow?
basics
~20 sAn array's length is set when you create it and can never change. To grow, you either create a bigger array and copy the elements over, or use a class like ArrayList that does that copying for you.
What are the ways to declare an array variable in Java, and is there a difference between int[] a and int a[]?
basics
~20 sYou can write the brackets after the type, like int[] a, or after the variable name, like int a[]. Both declare an array of ints and behave identically. The first style is preferred in Java.
How do you get the size of an array in Java, and why is it a field rather than a method?
basics
~10 sYou read the public length field, like a.length (no parentheses). It tells you how many elements the array has. It is fixed for the array's lifetime and you cannot change it.
How do you create (instantiate) an array in Java with the new keyword, and what does the size argument do?
basics
~20 sUse new with the element type and a length, like new int[5]. This allocates an array of 5 ints on the heap. The length is fixed for the array's lifetime, and you fill the slots by index afterwards.
What is the syntax for declaring a type parameter with multiple bounds in Java, and what does it mean?
basics
~20 sYou write <T extends A & B & C>. It means T must be a subtype of all of A, B, and C at once, so you can call methods from all of them on a T value.
What is an upper bound on a generic type parameter in Java, and why would you use one?
basics
~20 sAn upper bound uses the extends keyword to say a type parameter must be a given type or a subtype of it, like <T extends Number>. This lets you call that type's methods inside the class or method.
What is type erasure in Java generics, and what does the compiler do to the type parameters?
basics
~20 sType erasure means the generic type information (like the String in List<String>) is removed during compilation. At runtime, a List<String> and a List<Integer> are both just List. The compiler uses the types only for checking and then drops them.
What is a raw type in Java, and why does the language even allow you to write `List` without type arguments?
basics
~10 sA raw type is a generic class or interface used without its type arguments, like writing List instead of List<String>. Java allows it mainly so old pre-generics code (before Java 5) still compiles.
What is type erasure in Java generics, and what happens to generic type information when code is compiled to bytecode?
basics
~20 sType erasure means the compiler removes generic type arguments after checking them, so at runtime a List<String> is just a List. The type parameters are replaced with their bounds (usually Object), and casts are inserted automatically.
What is the fundamental difference between ArrayList and LinkedList in Java, and how does it affect their performance characteristics?
basics
~20 sArrayList stores elements in a resizable array, so reading any element by index is instant. LinkedList stores elements as separate nodes connected by links, so reading by index means walking the chain. ArrayList is faster for most uses.
What is an ArrayList in Java, and how does it store its elements?
basics
~10 sAn ArrayList is a resizable list backed by an array. You can add items without picking a size up front, and you read any item by its position (index) quickly.
What are the time complexities of common operations on ArrayList versus LinkedList, and when would you pick one over the other?
basics
~20 sArrayList gives fast index access (O(1)) but slow inserts/removes in the middle (O(n)). LinkedList is slow to reach an element by index (O(n)) but fast at adding/removing at the ends (O(1)). Use ArrayList by default.
What questions do you ask yourself to decide between a List, a Set, and a Map for a given task?
basics
~20 sUse a List when you need ordered items and duplicates are fine. Use a Set when you need unique items only. Use a Map when you look things up by a key. Pick based on whether you have keys, need uniqueness, or care about order.
What is the java.util.Collections class, and how does it differ from the Collection interface?
basics
~10 sCollection (no 's') is the interface that lists and sets implement. Collections (with 's') is a helper class full of static methods like sort, reverse, and emptyList that operate on those collections.
What is an empty catch block, and why is swallowing an exception considered a bug?
basics
~20 sAn empty catch block catches an exception but does nothing with it, so the error silently disappears. The program keeps running as if nothing went wrong, hiding real failures and making bugs very hard to find.
What is exception chaining in Java, and why would you wrap one exception inside another?
basics
~20 sException chaining means attaching the original exception (the cause) to a new exception when you wrap it. You pass the original to the new exception's constructor so you don't lose information about what really went wrong.
What is the difference between a checked and an unchecked exception in Java?
basics
~10 sA checked exception must be either caught or declared with throws, and the compiler enforces this. An unchecked exception (RuntimeException or Error and their subclasses) is not enforced by the compiler.
When designing a custom Java exception, what is the difference between a checked and an unchecked exception, and how do you decide which one to extend?
basics
~20 sA checked exception (extends Exception) must be declared or caught — the compiler forces it. An unchecked exception (extends RuntimeException) does not. Use checked for problems the caller can recover from, unchecked for programming bugs.
What is the fail-fast principle in Java, and why is validating inputs early considered good practice?
basics
~20 sFail-fast means you check for invalid inputs or bad state right away and stop immediately by throwing an error, instead of letting the program keep running with bad data and breaking later in a confusing place.
What is java.util.Scanner and how do you use it to read tokenized input from System.in?
basics
~20 sScanner is a class that reads and parses input. You wrap a source like System.in, then call methods such as nextInt(), nextDouble(), or nextLine() to read the next piece of input as a number or text.
What are the three standard streams in Java, what type is each, and what is each used for?
basics
~10 sJava has three standard streams: System.in for reading input, System.out for normal output, and System.err for errors. System.in is an InputStream; System.out and System.err are PrintStreams.
What is the java.io.File class, and what does a File object actually represent?
basics
~20 sjava.io.File represents a pathname (a name/location) for a file or directory, not the file's contents. Creating a File object does not create a file on disk; it just holds the path so you can ask about or act on it.
What is the difference between java.io.File and java.nio.file.Path/Files, and why is the NIO.2 API generally preferred for new code?
basics
~20 sFile is the old class for files and folders. Path (with the Files helper) is the newer NIO.2 API. Path/Files is preferred because it reports real errors (instead of returning false), supports symbolic links, file attributes, and works across different file systems.
What is the simplest modern way to read all text from a small file and write text to a file in Java, and what should you watch out for?
basics
~20 sUse the Files helper class: Files.readString(path) reads the whole file into one String, and Files.writeString(path, text) writes a String to a file. Both are fine for small files only, because they load everything into memory at once.
What is annotation processing (APT) in Java, and what can and cannot a processor do during compilation?
basics
~10 sAnnotation processing is a hook in the Java compiler that runs your code during compilation. It reads annotations in the source, and can generate brand-new source files. It cannot change existing files.
What is the difference between BigDecimal.equals() and BigDecimal.compareTo() when comparing two values, and which should you use to test numeric equality?
basics
~20 sequals() also checks scale, so 2.0 is not equal to 2.00. compareTo() ignores scale and compares the actual number, so 2.0 compareTo 2.00 returns 0. To check if two numbers are numerically equal, use compareTo() == 0.
Why should you use BigDecimal instead of double or float for monetary values?
basics
~10 sdouble and float store numbers in binary, so many decimals like 0.1 can't be represented exactly and small errors creep in. BigDecimal stores decimals exactly, so it's the right choice for money.
What is BigInteger in Java, when would you use it instead of long, and what does it mean that it is immutable?
basics
~10 sBigInteger holds whole numbers of any size, so it never overflows like long does. It is immutable: every operation returns a new BigInteger instead of changing the original.
What does the @Override annotation do, and why should you use it even though it's optional?
basics
~20 s@Override tells the compiler a method is meant to replace one from a parent class or interface. If it doesn't actually match a parent method, you get a compile error. It catches typos and wrong signatures early.
What are the three core types in java.net.http, and how do they fit together to make an HTTP call?
basics
~10 sYou build an HttpClient once, create an HttpRequest describing the URL/method/headers, then call client.send(request, handler). The result is an HttpResponse holding the status code, headers, and body.
What are Sequenced Collections (JEP 431, Java 21), and what problem do they solve?
basics
~20 sThey are new interfaces (SequencedCollection, SequencedSet, SequencedMap) added in Java 21 that give collections with a defined order a uniform way to access and add elements at the front and back, plus a reversed() view.
Explain MemorySegment and Arena, and how an Arena gives off-heap memory a safe, deterministic lifetime.
basics
~20 sA MemorySegment is a sized region of memory you can read and write. An Arena decides when that memory is freed: you allocate from the arena, and when you close the arena (usually with try-with-resources) all its memory is released at once and the segments become unusable.
What is the difference between HttpClient.send() and sendAsync(), and when would you use each?
basics
~10 ssend() is synchronous: it blocks the calling thread until the response arrives and returns the HttpResponse directly. sendAsync() is non-blocking: it returns immediately with a CompletableFuture that completes later with the response.
What is the difference between String.strip() and String.trim() in Java, and why was strip() added?
basics
~10 sBoth remove leading and trailing whitespace. trim() (old) only removes characters up to and including space (U+0020). strip() (Java 11) is Unicode-aware, so it also removes Unicode whitespace like non-breaking-aware spaces and ideographic spaces.