Advertisement

Top 50 Java interview questions and answers (2026)

The 50 Java questions worth preparing first, picked from all 300 on W3Teacher and spread across 20 topics. Each one has a short answer here and a full answer with examples and follow-ups on its own page.

20Beginner 20Intermediate 10Advanced 300questions in total
Jump to: Beginner · Intermediate · Advanced
Advertisement

Beginner Java interview questions

Q9 Beginner equals(), hashCode() & toString() Contracts

What is the default behavior of equals() and hashCode() inherited from Object, and why is it usually necessary to override them for value-based classes?

Short answer

Object's default equals() implementation performs reference equality (== comparison, true only if both references point to the exact same instance), and its default hashCode() is typically derived from the object's memory address/identity -- for a value-based class (like a Point…

Full answer with examples
Q11 Beginner Functional Interfaces & Method References

What is a functional interface, and what are the four core functional interfaces in java.util.function (Function, Predicate, Consumer, Supplier)?

Short answer

A functional interface has exactly one abstract method, making it eligible for lambda expression or method reference assignment -- Function transforms an input of type T into an output of type R (apply()); Predicate tests a condition, returning boolean (test()); Consumer accepts…

Full answer with examples
Q15 Beginner Inner Classes & Anonymous Classes

What is a non-static (inner) class in Java, and how does its relationship to an enclosing instance differ from a regular top-level class?

Short answer

A non-static inner class is defined within another class and holds an implicit reference to a specific instance of its enclosing class, meaning an inner class instance cannot exist independently of an associated outer instance and can freely access that outer instance's fields…

Full answer with examples
Q17 Beginner Java Date & Time API (java.time)

Why was the modern java.time API (introduced in Java 8) created to replace the legacy Date and Calendar classes, and what specific problems did the old classes have?

Short answer

The legacy java.util.Date and Calendar classes suffered from serious, well-documented design flaws: Date was mutable (making it unsafe to share/cache without defensive copying), had confusing zero-based month numbering (January = 0) and offset year values (years counted from…

Full answer with examples
Q18 Beginner Java Fundamentals: Syntax, Data Types & Operators

What are the eight primitive data types in Java, and how do they differ fundamentally from reference types like String or a custom class?

Short answer

The eight primitives are byte, short, int, long (integer types of increasing size), float, double (floating-point types), char (a single 16-bit Unicode character), and boolean (true/false) -- primitives store their actual value directly in the variable's own memory location…

Full answer with examples
Q19 Beginner Java Networking & HTTP Client

What is the modern java.net.http.HttpClient (introduced in Java 11), and how does it improve on the older HttpURLConnection for making HTTP requests?

Short answer

HttpClient provides a modern, fluent, builder-based API for constructing and sending HTTP requests (supporting HTTP/1.1 and HTTP/2, synchronous and asynchronous execution, and built-in support for common needs like redirects and timeouts) -- it significantly improves on the…

Full answer with examples
Q20 Beginner Java Platform Module System (JPMS)

What is the Java Platform Module System (JPMS, introduced in Java 9), and what core problem does it aim to solve compared to the traditional classpath-based approach?

Short answer

JPMS introduces explicit, JVM-enforced modules (declared via a module-info.java file) as a higher-level organizational unit above individual packages/JARs, letting you explicitly declare a module's dependencies (requires) and what it exposes to other modules (exports) -- this…

Full answer with examples

Intermediate Java interview questions

Q25 Intermediate Collections Framework

What are the key performance differences between ArrayList and LinkedList for common operations (random access, insertion/removal at various positions), and when would you choose one over the other?

Short answer

ArrayList backs its elements with a resizable array, giving O(1) random access (get(index)) but O(n) insertion/removal at arbitrary positions (requires shifting subsequent elements); LinkedList uses a doubly-linked list of nodes, giving O(1) insertion/removal once you already…

Full answer with examples
Q27 Intermediate Design Patterns in Java

How does the Builder pattern solve the "telescoping constructor" problem, and how would you implement it for a class with many optional parameters?

Short answer

The telescoping constructor problem arises when a class has many optional fields, leading to an unwieldy proliferation of overloaded constructors covering various combinations of provided parameters -- the Builder pattern instead uses a separate, often static nested Builder…

Full answer with examples
Q28 Intermediate Enums

How do you add fields, constructors, and methods to a Java enum, and how would you implement an enum representing planets with mass and radius that calculates surface gravity?

Short answer

Since each enum constant is a singleton instance, an enum can have instance fields (typically final, set via a private constructor invoked implicitly for each constant), and both regular instance methods (shared logic across all constants) and constant-specific method bodies…

Full answer with examples
Q29 Intermediate equals(), hashCode() & toString() Contracts

What are the five formal properties an equals() implementation must satisfy according to its documented contract (reflexive, symmetric, transitive, consistent, and null-handling)?

Short answer

Reflexive: x.equals(x) must always be true; Symmetric: x.equals(y) must equal y.equals(x); Transitive: if x.equals(y) and y.equals(z), then x.equals(z) must also be true; Consistent: repeated calls to x.equals(y) must return the same result as long as neither object's relevant…

Full answer with examples
Q31 Intermediate Functional Interfaces & Method References

What are the four kinds of method references in Java (static, instance-bound, instance-unbound, and constructor), and how does the compiler determine which form applies?

Short answer

Static method reference (ClassName::staticMethod) refers to a static method; bound instance method reference (instance::method) refers to a specific, already-existing object's instance method; unbound instance method reference (ClassName::instanceMethod) refers to an instance…

Full answer with examples
Q32 Intermediate Garbage Collection

How does the generational hypothesis (most objects die young) inform the JVM's generational heap structure (young generation, old generation), and how does a minor GC differ from a major/full GC?

Short answer

The generational hypothesis observes that in typical applications, the vast majority of objects become garbage very shortly after creation (like short-lived local variables or temporary calculation results), while a much smaller fraction survive long enough to become long-lived…

Full answer with examples
Q33 Intermediate Generics

What is type erasure, and how does it explain why generic type information is unavailable at runtime (e.g., why you can't do `if (obj instanceof List<String>)`)?

Short answer

Type erasure means the compiler uses generic type parameters ONLY for compile-time type checking, then removes (erases) them from the compiled bytecode, replacing an unbounded type parameter with Object (or its bound, if bounded) and inserting the necessary casts automatically…

Full answer with examples
Q34 Intermediate I/O & NIO

How does wrapping a FileInputStream in a BufferedInputStream (or FileReader in a BufferedReader) improve I/O performance, and what's the mechanism behind this improvement?

Short answer

Unbuffered I/O typically issues a separate, relatively expensive system call to the underlying OS for every single read/write operation (even reading just one byte), while a buffered wrapper reads (or writes) data in larger chunks into an internal in-memory buffer, satisfying…

Full answer with examples
Q35 Intermediate Inner Classes & Anonymous Classes

What is a static nested class, and why is it generally preferred over a non-static inner class when the nested class doesn't actually need access to the enclosing instance?

Short answer

A static nested class is declared with the static modifier, meaning it does NOT hold an implicit reference to any specific enclosing instance and can be instantiated independently (new Outer.Nested(), no outer instance required) -- it's generally preferred over a non-static…

Full answer with examples
Q36 Intermediate Interfaces & Abstract Classes

How do default methods (introduced in Java 8) let an interface provide a method implementation, and what problem were they specifically introduced to solve?

Short answer

A default method (marked with the default keyword) provides a concrete implementation directly within an interface, which implementing classes inherit automatically unless they choose to override it -- this was specifically introduced to solve the 'interface evolution' problem…

Full answer with examples
Q38 Intermediate Java Fundamentals: Syntax, Data Types & Operators

How does Java's operator precedence and associativity determine the evaluation order of a complex expression, and what are some common precedence-related mistakes?

Short answer

Operator precedence determines which operators bind more tightly (evaluated first) in an expression with multiple different operators (multiplication/division bind tighter than addition/subtraction, matching standard mathematical convention), and associativity determines the…

Full answer with examples
Q39 Intermediate Java Networking & HTTP Client

How would you make an asynchronous, non-blocking HTTP request using HttpClient's sendAsync() method, and how does the returned CompletableFuture integrate with the rest of an asynchronous pipeline?

Short answer

client.sendAsync(request, bodyHandler) immediately returns a CompletableFuture > without blocking the calling thread, letting you compose the eventual response using CompletableFuture's fluent chaining methods (thenApply(), thenAccept(), exceptionally()) to process the result…

Full answer with examples

Advanced Java interview questions

Q41 Advanced Annotations

How would you read custom annotations at runtime using reflection to implement annotation-driven behavior, such as a simple dependency injection or validation framework?

Short answer

Use java.lang.reflect classes (Class.getDeclaredMethods(), Method.getAnnotation(YourAnnotation.class), Field.isAnnotationPresent()) to inspect a class's structure at runtime, checking for the presence of your custom RUNTIME-retention annotation and extracting its element values…

Full answer with examples
Q43 Advanced Build Tools: Maven & Gradle

How does Maven's dependency resolution algorithm handle transitive dependency version conflicts, and what is the "nearest definition wins" rule?

Short answer

When multiple dependencies (directly or transitively) require different versions of the same library, Maven resolves the conflict using "nearest definition wins": the version declared at the shallowest depth in the dependency tree (closest to your project's own pom.xml) takes…

Full answer with examples
Q44 Advanced Class Loading & Bytecode Verification

How would you implement a custom ClassLoader to load classes from a non-standard source, such as loading plugin JARs dynamically at runtime, and what challenges arise with class unloading?

Short answer

A custom ClassLoader extends ClassLoader (or URLClassLoader for JAR/URL-based loading) and overrides findClass() to define how to locate and read the raw bytecode from your custom source (a database, a plugin directory scanned at runtime, a network location), then calls…

Full answer with examples
Q46 Advanced Concurrency & Threads

How does java.util.concurrent's ReentrantLock differ from the synchronized keyword, and what additional capabilities does it provide (tryLock, fairness, interruptible locking)?

Short answer

ReentrantLock provides everything synchronized offers (mutual exclusion, reentrancy -- a thread already holding the lock can re-acquire it without deadlocking itself) plus additional capabilities unavailable with synchronized: tryLock() (attempt to acquire without blocking…

Full answer with examples
Q47 Advanced Design Patterns in Java

How would you implement the Observer pattern in Java, and how does it compare to using the built-in PropertyChangeSupport or a reactive streams library?

Short answer

The Observer pattern defines a one-to-many dependency where a subject notifies registered observers of state changes -- implementable manually with a List and a notify loop, via the JDK's built-in (though somewhat dated) java.beans.PropertyChangeSupport for JavaBean-style…

Full answer with examples
Q48 Advanced Enums

How would you implement the Strategy pattern using an enum with constant-specific method bodies, and how does this compare to a traditional interface-based Strategy implementation?

Short answer

An enum can have each individual constant override an abstract method with its own unique implementation (a "constant-specific class body"), letting the enum itself directly encapsulate a fixed, closed set of interchangeable algorithms/strategies without needing separate…

Full answer with examples
Q49 Advanced equals(), hashCode() & toString() Contracts

How does the getClass() versus instanceof choice in an equals() implementation affect whether subclasses can be considered equal to their superclass instances, and what's the Liskov Substitution Principle tension involved?

Short answer

Using getClass() == getClass() comparison in equals() strictly requires both objects to be the exact same runtime class (a subclass instance is never equal to a superclass instance, even if all inherited fields match), which preserves the transitivity contract robustly across…

Full answer with examples
Q50 Advanced Exceptions

How does exception chaining (via the cause mechanism, initCause() or a constructor accepting a Throwable) preserve the original root-cause exception when wrapping and rethrowing a different exception type, and why does this matter for debugging?

Short answer

When catching a lower-level exception and throwing a different, higher-level exception more meaningful to the caller (a common pattern for translating a checked exception into an unchecked one, or abstracting away an implementation detail), passing the original exception as the…

Full answer with examples

Can you answer these under pressure?

Run a timed Java mock interview: random questions, answer out loud, reveal the model answer and get a readiness score you can share.