Skip to content
SparkTime, home
Java From Zero to Job-Ready
Lessons
1 · Java Foundations
2 · Object-Oriented Java
3 · Core Java
4 · Collections and Generics
5 · Functional Java
6 · The JVM and Concurrency
7 · Tools and Craft
8 · Databases and JDBC
9 · Web and Spring
10 · Persistence with JPA
11 · Secure, Tested, Production-Ready
12 · Interviews and Readiness
Lesson 40 of 41

Lesson 40 · Interviews and Readiness

Java Interview Concepts, Part 1: Core Java, Collections, Functional Java, the JVM and Concurrency

Prepare for Java interviews by concept: for each topic a short answer, the real explanation, a small example, the usual follow-up question and the common incorrect answer, covering the language, collections, streams, the JVM and concurrency.

On this page

Key takeaways

  • A good interview answer has five parts: a short answer, the real explanation, a small example, the follow-up you expect, and the common wrong answer you avoid.
  • The language questions come back to a few ideas: references and pass-by-value, immutability, the equals and hashCode contract, and what generics erase.
  • The collections questions are about choosing the right structure and about how HashMap works: hash, bucket, equals, resize and the treeification of long chains.
  • The runtime and concurrency questions are about memory (stack, heap, garbage collection), visibility and atomicity (volatile versus synchronized and atomics), and choosing executors and virtual threads sensibly.
  • Say what you do not know. A precise "I would check the documentation for that" is better than a confident wrong answer.

Interviews ask about concepts you already used. This article collects the most common ones, in the same format for each: a short answer you can say in ten seconds, the real explanation, a small example, the follow-up that usually comes next, and the common incorrect answer to avoid. Each entry names the article that teaches it with code and real output.

How to use this article

#

Do not memorise the answers. Read an entry, close the page, and explain it aloud with your own example. Then check what you missed. If you cannot explain an entry, go back to the article in the "Learn more" line and run its program.

Language fundamentals

#

JDK, JRE and JVM

#
  • Short answer: The JVM runs bytecode, the JRE is the JVM plus libraries, and the JDK adds the compiler and tools. Today you install a JDK.
  • Explanation: javac compiles .java to .class bytecode. The JVM loads and runs it, interpreting and compiling hot code with the JIT. The same bytecode runs on any platform with a JVM.
  • Example: javac Main.java then java Main.
  • Follow-up: "Is Java interpreted or compiled?" Both: compiled to bytecode, then interpreted and JIT-compiled at run time.
  • Common wrong answer: "Java is platform independent" without saying that it is the bytecode and the JVM that are.
  • Learn more: article 1, article 18.

Primitives, wrappers and overflow

#
  • Short answer: Primitives hold values, wrappers are objects. Integer arithmetic wraps around silently on overflow.
  • Explanation: int is 32 bits, so Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. Use Math.addExact to throw instead, long for larger ranges and BigDecimal for exact decimals. Floating-point (double) cannot represent most decimals exactly, so never use it for money.
  • Follow-up: "Integer a = 127, b = 127; a == b?" true for values in the small cache (-128 to 127), false beyond it for separately boxed values, so compare wrappers with equals.
  • Common wrong answer: "== compares values" for objects.
  • Learn more: article 2.

Pass by value

#
  • Short answer: Java always passes by value. For objects, the value is a copy of the reference.
  • Explanation: A method can change the object a reference points to, and cannot make the caller's variable point somewhere else. Reassigning the parameter only changes the local copy.
  • Follow-up: "Then how can a method modify my list?" Because both references point to the same list.
  • Common wrong answer: "Objects are passed by reference."
  • Learn more: article 3.

Encapsulation, inheritance, polymorphism, abstraction

#
  • Short answer: Hide state behind methods, reuse by extending, call the right method at run time, and depend on interfaces.
  • Explanation: Encapsulation keeps fields private so invariants hold. Polymorphism means the method that runs depends on the object's real type. Prefer composition over inheritance, because inheritance couples the subclass to the parent's implementation.
  • Follow-up: "Abstract class or interface?" Interface for a capability or contract (a class can implement many), abstract class when subclasses share state and code.
  • Common wrong answer: Listing the four words without an example.
  • Learn more: articles 4 to 6.

Overloading versus overriding

#
  • Short answer: Overloading is the same name with different parameters, chosen at compile time. Overriding replaces an inherited method, chosen at run time.
  • Follow-up: "Can you override a static method?" No, it is hidden. Use @Override so the compiler checks you.
  • Learn more: article 5.

Core classes

#

The equals and hashCode contract

#
  • Short answer: Equal objects must have equal hash codes. If you override one, override both.
  • Explanation: HashMap and HashSet use hashCode to find a bucket and equals to confirm a match. Break the contract and objects "disappear" from hash collections. equals must be reflexive, symmetric, transitive, consistent and false for null.
  • Follow-up: "Can unequal objects share a hash code?" Yes, that is a collision.
  • Common wrong answer: "hashCode must be unique."
  • Learn more: article 7.

String immutability and the pool

#
  • Short answer: Strings cannot change, so they are safe to share, cache and use as keys.
  • Explanation: Every "change" creates a new string. Literals are interned in a pool, so == may be true for literals and false for new String(...). Use equals. Build in loops with StringBuilder.
  • Follow-up: "Why is it a good HashMap key?" Its hash code cannot change.
  • Learn more: article 8.

Checked and unchecked exceptions

#
  • Short answer: Checked exceptions must be handled or declared, unchecked ones (subclasses of RuntimeException) need not be.
  • Explanation: Use checked for recoverable conditions the caller must consider, unchecked for programming errors. Always close resources with try-with-resources, and keep the cause when wrapping. Never swallow an exception silently.
  • Follow-up: "What does finally do if there is a return in try?" It still runs.
  • Common wrong answer: "Error and Exception are the same."
  • Learn more: article 10.

Records, enums and sealed types

#
  • Short answer: Records are immutable data carriers, enums are fixed sets of constants, sealed types limit which classes may extend them.
  • Explanation: A record generates the constructor, accessors, equals, hashCode and toString. Sealed hierarchies let a switch be exhaustive without default. Store enums by name, never by ordinal.
  • Learn more: article 9.

Collections

#

ArrayList versus LinkedList

#
  • Short answer: Use ArrayList almost always. Index access is O(1), and appends are amortised O(1).
  • Explanation: LinkedList has O(1) insertion at known nodes but O(n) access and poor cache behaviour. For queues and stacks prefer ArrayDeque.
  • Common wrong answer: "LinkedList is faster for insertion", ignoring that finding the position is O(n).
  • Learn more: article 11.

How HashMap works

#
  • Short answer: An array of buckets. hashCode picks the bucket, equals finds the key, and long chains become trees.
  • Explanation: put computes the hash, indexes the table, and walks the bucket comparing with equals. When the table passes the load factor (0.75), it doubles and entries are redistributed. A bucket with many entries is converted to a balanced tree, so the worst case is O(log n) instead of O(n) (when keys are comparable).
  • Example: The course measured a toy implementation: 50 entries, 128 buckets after 5 resizes, longest chain 1 with a good hash and 50 with a constant one.
  • Follow-up: "Is HashMap thread-safe?" No. Use ConcurrentHashMap. "Does it allow null?" One null key and null values.
  • Common wrong answer: "It is always O(1)."
  • Learn more: article 12.

HashMap, LinkedHashMap, TreeMap

#
  • Short answer: Unordered, insertion-ordered, and sorted by key (O(log n)).
  • Learn more: article 12, article 13.

Comparable versus Comparator

#
  • Short answer: Comparable is the natural order inside the class, Comparator is an external, replaceable order.
  • Explanation: Keep compareTo consistent with equals, and never subtract integers to compare (overflow), use Integer.compare.
  • Learn more: article 13.

Fail-fast iterators and ConcurrentModificationException

#
  • Short answer: Modifying a collection while iterating it throws.
  • Explanation: Use Iterator.remove, removeIf, or build a new collection. Concurrent collections have weakly consistent iterators instead.
  • Learn more: article 11.

Generics and functional Java

#

Type erasure

#
  • Short answer: Generic type information exists at compile time and is erased at run time.
  • Explanation: List<String> and List<Integer> are the same class at run time, so you cannot do new T(), instanceof List<String> or create generic arrays. This is why TypeReference exists in libraries such as Jackson.
  • Follow-up: "What is PECS?" Producer extends, consumer super: use ? extends T to read from a structure and ? super T to write into it.
  • Common wrong answer: "Generics exist at run time."
  • Learn more: article 14.

Lambdas and functional interfaces

#
  • Short answer: A lambda is a short implementation of an interface with one abstract method.
  • Explanation: Variables captured by a lambda must be effectively final. this inside a lambda is the enclosing object, unlike an anonymous class.
  • Learn more: article 15.

Streams

#
  • Short answer: A declarative pipeline: source, lazy intermediate operations, one terminal operation.
  • Explanation: Nothing runs until the terminal operation. A stream can be consumed once. Avoid side effects in map and filter. Parallel streams help only for large CPU-bound work with no shared state, and often hurt.
  • Follow-up: "map versus flatMap?" One output per input versus flattening many.
  • Common wrong answer: "Streams are always faster than loops."
  • Learn more: article 16.

Optional

#
  • Short answer: A return type that says "maybe no value". Do not use it for fields or parameters, and never call get() without checking.
  • Explanation: Prefer orElse, orElseGet, orElseThrow, map and ifPresent.
  • Learn more: article 17.

The JVM

#

Stack and heap

#
  • Short answer: Each thread has a stack of frames (locals and calls). Objects live on the shared heap.
  • Explanation: Infinite recursion gives StackOverflowError. Retained objects that are no longer needed (a growing static map, listeners never removed) give OutOfMemoryError.
  • Learn more: article 18.

Garbage collection

#
  • Short answer: The JVM frees objects that are no longer reachable from any root.
  • Explanation: Collectors are generational: most objects die young. There is no guarantee when a collection happens, and System.gc() is only a hint. A "memory leak" in Java is an object that is still referenced but never used again.
  • Follow-up: "How do you investigate a leak?" A heap dump and the class histogram (jcmd), then find what holds the references (article 22).
  • Common wrong answer: "Java cannot leak memory."

JIT compilation and warm-up

#
  • Short answer: Hot code is compiled to machine code at run time, so the first calls are slower.
  • Explanation: This is why microbenchmarks written with a simple loop and System.nanoTime are unreliable. Use a benchmarking tool such as JMH.

Concurrency

#

Race condition, atomicity, visibility

#
  • Short answer: A race is a result that depends on timing. count++ is read, add, write, so it is not atomic.
  • Explanation: In the course, two threads incrementing a plain counter lost updates. Fixes that all reached exactly 2,000,000: synchronized, AtomicInteger, a ReentrantLock and LongAdder.
  • Learn more: article 19.

volatile versus synchronized

#
  • Short answer: volatile gives visibility and ordering for one variable. synchronized gives mutual exclusion plus visibility.
  • Explanation: volatile does not make count++ atomic. Use it for flags such as running, and use locks or atomics for compound actions.
  • Common wrong answer: "volatile makes it thread-safe."

Deadlock

#
  • Short answer: Two or more threads each wait for a lock the other holds.
  • Explanation: Prevent it by always acquiring locks in the same order, holding locks briefly and using timeouts (tryLock). Diagnose with a thread dump (jcmd <pid> Thread.print), which reports deadlocks.

Executors, CompletableFuture and virtual threads

#
  • Short answer: Do not create threads by hand. Submit tasks to an executor.
  • Explanation: A fixed pool bounds concurrency. CompletableFuture composes asynchronous steps. Virtual threads (Java 21, JEP 444) are cheap threads for blocking I/O workloads: the course ran 10,000 of them. They do not make CPU-bound code faster, and you should not pool them. Be careful with long synchronized blocks around blocking calls, which can pin the carrier thread.
  • Follow-up: "What does ConcurrentHashMap give you?" Thread-safe operations without locking the whole map, and atomic methods such as merge and computeIfAbsent.
  • Common wrong answer: "Virtual threads replace the need to understand thread safety."
  • Learn more: article 20.

Files, serialization and tools

#

try-with-resources and NIO.2

#
  • Short answer: Anything that implements AutoCloseable is closed automatically, in reverse order. Prefer java.nio.file.Files and Path to the old File.
  • Learn more: article 21.

Java serialization

#
  • Short answer: Avoid native Java deserialization of untrusted data. It has been the source of serious vulnerabilities.
  • Explanation: Prefer JSON or another explicit format. If you must deserialize, use a serialization filter (JEP 290) with an allow-list.

Maven scopes and the lifecycle

#
  • Short answer: compile, runtime, test and provided say when a dependency is on the classpath. Running a phase runs all the phases before it.
  • Follow-up: "Why NoClassDefFoundError from a jar that compiled?" The jar did not contain its dependencies (article 23).

Practice questions

#

Exercise 1

  1. Explain == versus equals and give a case where == surprises you.
  2. Why must a HashMap key be effectively immutable?
  3. What happens when you resize a HashMap, and why?
  4. Why can list.remove(i) inside a for-each loop fail?
  5. What is the difference between Runnable, Callable and Supplier?
  6. When would you use ConcurrentHashMap.merge?
  7. Explain how you would find the cause of a hung application.
Sample answers
  1. == compares references for objects, equals compares content as the class defines it. new String("a") == "a" is false, and boxed Integer values beyond the small cache differ.
  2. If the key changes after insertion, its hash code changes, so the entry sits in the wrong bucket and cannot be found.
  3. The table doubles and entries are redistributed by their hash, to keep chains short. It is O(n), amortised over many inserts.
  4. The iterator detects a structural change and throws ConcurrentModificationException. Use Iterator.remove or removeIf.
  5. Runnable returns nothing and cannot throw checked exceptions, Callable returns a value and may throw, Supplier returns a value with no input and no checked exception.
  6. To count or combine values atomically across threads, for example word counts, instead of get-then-put.
  7. Take several thread dumps a few seconds apart, look for blocked threads and the locks they wait on or for a deadlock report, check the logs, then form one hypothesis at a time.

Common mistakes in interviews

#
  • Memorising definitions without an example you can write.
  • Confident wrong answers instead of "I would check".
  • Not asking what the interviewer means (which Java version, what scale).
  • Saying "always" and "never" about performance advice.
  • Describing a pattern but not the problem it solves.

Where to go next

#

Sources & further reading

  1. docs.oracle.com
  2. docs.oracle.com
  3. openjdk.org

Connected lessons

Linked from 1 guide

Other pages in the library that point here.

  • Guide · Technology

    Java Essentials for DSA

  • Guide · Technology

    Heaps and Priority Queues

  • Course · Technology

    DSA From Zero to Job-Ready: A Practical Guide with Java