Java Interview Questions: 18 Answers With Code-Level Samples (2026)

18 Java interview questions with sample answers: equals and hashCode, HashMap internals, JVM memory, concurrency, streams, records and virtual threads.

By OphyAI Team • • Updated October 16, 2026 • 2747 words

Last updated: October 2026

Quick Answer

Java interviewers test whether you understand how the language and the JVM behave, not whether you can recite definitions: object equality and hashing, collections internals, memory and garbage collection, concurrency, and modern features such as streams, records and virtual threads. Expect a mix of short concept questions, a live coding problem and questions about the code on your resume. Practice explaining each concept aloud in OphyAI Interview Practice, and drill the coding rounds in OphyAI Coding Interview.

#QuestionWhat it tests
1equals() and hashCode()Object contracts
2How HashMap worksCollections internals
3String immutability and the poolMemory and design
4== vs equals()Reference vs value
5Checked vs unchecked exceptionsError design
6Abstract class vs interfaceOOP design
7JVM memory areasRuntime knowledge
8Garbage collectionMemory management
9synchronized vs volatileConcurrency basics
10ArrayList vs LinkedListComplexity tradeoffs

The Questions, With Sample Answers

1. “What is the contract between equals() and hashCode()?”

Why they ask. It exposes whether you know how hash-based collections find objects.

Sample answer. “If two objects are equal according to equals(), they must return the same hashCode(). The reverse does not have to hold, because different objects can share a hash code. If I override equals() without hashCode(), a HashMap or HashSet can fail to find an object I just inserted, because the two equal objects land in different buckets. I implement both from the same fields, and I use Objects.equals and Objects.hash, or let the IDE or a record generate them. For mutable keys I avoid fields that change after insertion.”

Weak answers. Reciting the rule with no consequence, or saying hashCode must be unique.

2. “How does a HashMap work internally?”

Why they ask. It is the most common collections internals question.

Sample answer. “A HashMap keeps an array of buckets. For a key, it computes hashCode(), spreads the bits, and uses the result to pick a bucket index. Colliding entries in the same bucket are chained as a linked list, and in modern Java a long chain is converted to a balanced tree to keep lookups from degrading to linear. When the number of entries passes capacity times the load factor, which defaults to 0.75, the table resizes and entries are redistributed. Average get and put are constant time. Keys need correct equals and hashCode, and HashMap is not thread safe.”

Weak answers. Describing it as “key-value pairs” with no buckets, hashing or resize.

3. “Why is String immutable, and what is the string pool?”

Why they ask. It connects language design to security, caching and thread safety.

Sample answer. “A String cannot change after creation. That makes it safe to share between threads, safe to use as a map key because its hash code does not change, and safe for security-sensitive values like class names and file paths. The string pool stores literals so identical literals can share one object. Using new String creates a separate object. Because strings are immutable, concatenating in a loop creates many temporary objects, so I use StringBuilder for repeated appends in a loop.”

Weak answers. Saying immutable means the variable cannot be reassigned.

4. “What is the difference between == and equals()?”

Why they ask. It is a quick filter for reference versus value understanding.

Sample answer. “For objects, == compares references, whether two variables point to the same object, while equals compares logical equality as the class defines it. For primitives, == compares values. Two Strings with the same characters can be equal but not the same object. I also watch Integer caching: boxed values in a small range are cached, so == can appear to work for small numbers and then fail for larger ones. I use equals for objects and Objects.equals when either side may be null.”

Weak answers. Saying they are the same for Strings.

5. “What is the difference between checked and unchecked exceptions?”

Why they ask. It shows how you design error handling.

Sample answer. “Checked exceptions extend Exception but not RuntimeException, and the compiler forces callers to catch or declare them. Unchecked exceptions are RuntimeException and its subclasses, plus Errors. I use checked exceptions when the caller can reasonably recover, like a missing file, and unchecked exceptions for programming errors, like a null argument. I never swallow exceptions silently, I wrap with the cause so the stack trace survives, and I use try-with-resources so resources close even when exceptions occur.”

Weak answers. Listing examples with no guidance on when to use each.

6. “Abstract class or interface: when do you use each?”

Why they ask. It tests design judgment.

Sample answer. “An interface defines a capability a class promises to provide, and a class can implement many. Since Java 8, interfaces can have default and static methods, so they can share behavior without state. An abstract class can hold fields and constructors and shares a base implementation among related classes, but a class extends only one. I start with an interface for the contract and add an abstract base class only when subclasses share state or significant code. Sealed interfaces, available since Java 17, let me restrict who can implement them.”

Weak answers. Saying interfaces cannot have methods with bodies.

7. “What are the main JVM memory areas?”

Why they ask. It shows whether you can reason about memory errors.

Sample answer. “Objects live on the heap, which is shared and garbage collected. Each thread has its own stack holding frames with local variables and references. Class metadata lives in Metaspace, which replaced the permanent generation in Java 8. There is also native memory used by the JVM, direct buffers and threads. An OutOfMemoryError in the heap suggests a leak or undersized heap, while a StackOverflowError usually means runaway recursion. I diagnose with heap dumps and a profiler instead of guessing.”

Weak answers. Confusing stack and heap or naming only the heap.

8. “How does garbage collection work?”

Why they ask. It tests whether you can tune and debug production Java.

Sample answer. “The collector reclaims objects that are no longer reachable from roots like thread stacks and static fields. Most JVM collectors are generational: new objects start in a young region where most die quickly, and survivors are promoted to an old region. G1 has been the default collector since Java 9, with low-pause options like ZGC for latency-sensitive services. I do not call System.gc. If I see long pauses or frequent collections, I check GC logs, allocation rate and object retention before changing flags.”

Weak answers. Saying Java has no memory leaks, or recommending System.gc.

9. “What is the difference between synchronized and volatile?”

Why they ask. It is the entry question for concurrency.

Sample answer. “Volatile guarantees visibility and ordering for a single variable: a write by one thread is seen by others. It does not make compound actions like increment atomic. Synchronized provides mutual exclusion and visibility for a block, so only one thread runs the section at a time. For a counter, I would use AtomicInteger or a lock. I use volatile for simple flags, synchronized or java.util.concurrent classes for compound updates, and I keep critical sections small to avoid contention and deadlock.”

Weak answers. Saying volatile makes a variable thread safe in general.

10. “ArrayList or LinkedList?”

Why they ask. It tests complexity thinking against real hardware.

Sample answer. “ArrayList is backed by an array, so index access is constant time and iteration is cache friendly. Adding at the end is amortized constant time, but inserting in the middle shifts elements. LinkedList has constant-time insertion at a known node, but finding that node is linear and each element carries pointer overhead. In practice ArrayList is the default, and I use ArrayDeque for queue and stack behavior. I choose LinkedList rarely, and only when I profile a need.”

Weak answers. Claiming LinkedList is faster for inserts without mentioning the search.

11. “How do you make a class immutable?”

Why they ask. It tests defensive design and concurrency awareness.

Sample answer. “Make the class final, make all fields private and final, set them only in the constructor, provide no setters, and make defensive copies of mutable inputs and outputs, such as dates and collections. Immutable objects are thread safe without locking and safe as map keys. Since Java 16, records give me a concise immutable data carrier, though a record holding a mutable list is only shallowly immutable, so I still copy the list with List.copyOf.”

Weak answers. Saying final fields alone are enough.

12. “What are streams, and when would you avoid them?”

Why they ask. It checks modern Java fluency and judgment.

Sample answer. “Streams, added in Java 8, process a sequence of elements with a pipeline of operations: filter, map, collect. They are lazy until a terminal operation runs. I use them for clear transformations such as grouping or mapping a list. I avoid them when a plain loop is clearer, when I need checked exceptions, or when the operation has side effects. Parallel streams use the common fork-join pool and can hurt performance for small or blocking workloads, so I measure before using them.”

Weak answers. Saying streams are always faster than loops.

13. “How do threads, ExecutorService and CompletableFuture differ?”

Why they ask. It tests how you structure concurrent work.

Sample answer. “Creating raw Thread objects is expensive and hard to manage. An ExecutorService manages a pool and a queue, so tasks run on reused threads and I can control sizing and shutdown. CompletableFuture lets me compose asynchronous steps with thenApply and thenCombine and handle errors without blocking. I pick pool sizes based on whether work is CPU bound or I/O bound, I always shut executors down, and I name my threads for debugging.”

Weak answers. Creating a new thread per request.

14. “What are virtual threads, and when do they help?”

Why they ask. It shows whether you follow current Java.

Sample answer. “Virtual threads, finalized in Java 21 (JEP 444), are lightweight threads managed by the JVM rather than one-to-one with operating system threads. They let a server handle many blocking I/O tasks with the simple thread-per-request style. They help when tasks spend time waiting on network or disk, and they do not speed up CPU-bound work. I avoid pooling them, I watch for pinning inside synchronized blocks, and I confirm my libraries behave well with them.”

Weak answers. Describing them as faster threads for everything.

15. “What are records, and how do they differ from regular classes?”

Why they ask. It tests recent language knowledge.

Sample answer. “A record, standardized in Java 16 (JEP 395), is a concise way to declare an immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode and toString from the components. Records are final and cannot extend other classes, though they can implement interfaces. I use them for DTOs, value objects and map keys. I use a regular class when I need mutable state, inheritance or hidden representation.”

Weak answers. Saying records are the same as Lombok.

16. “How does Optional help, and how can it be misused?”

Why they ask. It tests null-safety practice.

Sample answer. “Optional represents a return value that may be absent, which forces the caller to handle that case. I use map, flatMap, orElse and orElseThrow instead of calling get blindly. I do not use Optional for fields, method parameters or collections, where it adds noise, and I return an empty collection instead of an Optional of a list. Optional helps at API boundaries, but it does not replace validating inputs.”

Weak answers. Calling get() without checking, or using Optional everywhere.

17. “Explain dependency injection and how Spring uses it.”

Why they ask. Many Java roles are Spring roles, and this reveals whether you understand design, not just annotations.

Sample answer. “Dependency injection means a class receives its collaborators instead of creating them, which makes code easier to test and swap. Spring’s container creates and wires beans from configuration and annotations. I prefer constructor injection because dependencies are explicit and the fields can be final, which keeps the object immutable and easy to test with mocks. I keep beans stateless by default, since the default singleton scope is shared across threads.”

Weak answers. Listing annotations with no explanation of why DI exists.

18. “Walk me through how you would debug a slow Java service.”

Why they ask. It tests structured troubleshooting.

Sample answer. “I start with measurement: is it CPU, memory, I/O or waiting on a dependency? I look at metrics and logs, then take thread dumps to see if threads are blocked or spinning, check GC logs for pauses, and profile the hot paths. I check database queries, connection pool limits and downstream calls. I change one thing at a time and verify with a load test, and I write down what the fix improved.”

Weak answers. Jumping straight to tuning flags or guessing a cause.

How to Practice These

Say each answer aloud in under two minutes in OphyAI Interview Practice, which runs voice or text mock interviews with follow-up questions, a transcript and per-answer feedback, and use OphyAI Coding Interview to rehearse the live coding and system design rounds. For a live video interview, OphyAI Interview Copilot gives real-time suggestions on Zoom, Microsoft Teams and Google Meet, but check the employer’s rules first in the tracker of employers and their AI rules. Start practicing →

Pair this page with the technical interview prep guide for software engineers, the SQL interview questions and the Python interview questions.

Frequently Asked Questions

What Java topics are asked most in interviews?

Candidates and interview guides report collections internals (HashMap, ArrayList), equals and hashCode, strings, exceptions, OOP design, JVM memory, garbage collection and concurrency. Senior roles add streams, the java.util.concurrent package, Spring and performance debugging. Prepare the fundamentals first, then the area your target posting names.

Which Java version should I prepare for?

Prepare for the version in the job posting. Java 8, 11, 17 and 21 are long-term support releases that employers commonly run. Know the Java 8 basics (lambdas, streams, Optional), plus records and sealed classes from Java 16 and 17, and virtual threads from Java 21.

How many Java questions should I expect in a coding round?

Most coding rounds are one or two problems of 30 to 45 minutes, often on arrays, strings, collections and recursion, and you choose the language. Concept questions often come in a separate technical conversation. Ask the recruiter for the format.

Do I need to know Spring for a Java interview?

For backend roles at many US employers, Spring Boot is common, so expect dependency injection, REST controllers, transactions and testing questions. For general Java roles or new graduate positions, language fundamentals matter more. Read the posting and check the company guide for the team’s stack.

How do I explain Java concepts without sounding like I memorized them?

Use a one-sentence definition, a short example from code you wrote, and a tradeoff. For instance, define HashMap collisions, then mention a bug you fixed or a key class where you implemented hashCode. Interviewers follow up on your example, so choose one you can discuss for two minutes.

Can I use AI during a Java coding interview?

Only if the employer allows it. Many companies disclose rules in the invitation, and some assessments are proctored. Ask your recruiter, follow the stated policy, and check the tracker of employers and their AI rules. Practicing with AI beforehand is always a safe use.

Sources and verification notes

Sources checked October 2026. The pages below could not be opened from the publishing environment, so the version facts (records in Java 16, sealed classes in Java 17, virtual threads in Java 21, G1 as the default collector since Java 9, Metaspace replacing the permanent generation in Java 8) come from standard Java documentation knowledge and should be verified against the linked pages. The sample answers are original templates, not employer-published questions.

Tags:

java interview questions software engineer interview technical interview backend interview coding interview

Turn the advice into a realistic practice session

Run a role-specific mock interview, review feedback across four scoring areas, and repeat the answers that need work.