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
- 21File I/O and Serialization
- 22Debugging: Errors, Stack Traces, the Debugger and Logging
- 23Maven: What It Does and How to Use It
- 24Git for Java Projects: Commits, Branches, Merging and Pull Requests
- 25Testing with JUnit and Mockito: Unit Tests, Mocks and Their Limits
- 26Project 1: Build an Expense Tracker CLI in Plain Java
8 · Databases and JDBC
9 · Web and Spring
10 · Persistence with JPA
11 · Secure, Tested, Production-Ready
- 36Security Fundamentals and Spring Security: Passwords, JWT, Access Control, CORS and Secrets
- 37Testing Spring Boot Applications: Slice Tests, MockMvc, Real Databases and the Test Pyramid
- 38Production Practices: Configuration, Logging, Docker and Health Checks for Spring Boot
- 39Project 3: The Job Application Tracker API, Assembled and Reviewed
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.
For
Learners preparing for junior and mid-level Java backend interviews who have worked through the language and runtime articles.
Level
Before you start
Articles 1 to 22 of this course. Every statement here is explained, with the programs that demonstrate it, in the article named in the "Learn more" line of each concept.
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:
javaccompiles.javato.classbytecode. 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.javathenjava 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:
intis 32 bits, soInteger.MAX_VALUE + 1isInteger.MIN_VALUE. UseMath.addExactto throw instead,longfor larger ranges andBigDecimalfor 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?"truefor values in the small cache (-128 to 127),falsebeyond it for separately boxed values, so compare wrappers withequals. - 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
@Overrideso 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:
HashMapandHashSetusehashCodeto find a bucket andequalsto confirm a match. Break the contract and objects "disappear" from hash collections.equalsmust be reflexive, symmetric, transitive, consistent and false fornull. - 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 fornew String(...). Useequals. Build in loops withStringBuilder. - Follow-up: "Why is it a good
HashMapkey?" 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
finallydo if there is areturnintry?" It still runs. - Common wrong answer: "
ErrorandExceptionare 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,hashCodeandtoString. Sealed hierarchies let aswitchbe exhaustive withoutdefault. Store enums by name, never by ordinal. - Learn more: article 9.
Collections
#ArrayList versus LinkedList
#- Short answer: Use
ArrayListalmost always. Index access is O(1), and appends are amortised O(1). - Explanation:
LinkedListhas O(1) insertion at known nodes but O(n) access and poor cache behaviour. For queues and stacks preferArrayDeque. - Common wrong answer: "
LinkedListis faster for insertion", ignoring that finding the position is O(n). - Learn more: article 11.
How HashMap works
#- Short answer: An array of buckets.
hashCodepicks the bucket,equalsfinds the key, and long chains become trees. - Explanation:
putcomputes the hash, indexes the table, and walks the bucket comparing withequals. 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
HashMapthread-safe?" No. UseConcurrentHashMap. "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:
Comparableis the natural order inside the class,Comparatoris an external, replaceable order. - Explanation: Keep
compareToconsistent withequals, and never subtract integers to compare (overflow), useInteger.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>andList<Integer>are the same class at run time, so you cannot donew T(),instanceof List<String>or create generic arrays. This is whyTypeReferenceexists in libraries such as Jackson. - Follow-up: "What is PECS?" Producer
extends, consumersuper: use? extends Tto read from a structure and? super Tto 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.
thisinside 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
mapandfilter. Parallel streams help only for large CPU-bound work with no shared state, and often hurt. - Follow-up: "
mapversusflatMap?" 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,mapandifPresent. - 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) giveOutOfMemoryError. - 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.nanoTimeare 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, aReentrantLockandLongAdder. - Learn more: article 19.
volatile versus synchronized
#- Short answer:
volatilegives visibility and ordering for one variable.synchronizedgives mutual exclusion plus visibility. - Explanation:
volatiledoes not makecount++atomic. Use it for flags such asrunning, and use locks or atomics for compound actions. - Common wrong answer: "
volatilemakes 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.
CompletableFuturecomposes 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 longsynchronizedblocks around blocking calls, which can pin the carrier thread. - Follow-up: "What does
ConcurrentHashMapgive you?" Thread-safe operations without locking the whole map, and atomic methods such asmergeandcomputeIfAbsent. - 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
AutoCloseableis closed automatically, in reverse order. Preferjava.nio.file.FilesandPathto the oldFile. - 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,testandprovidedsay when a dependency is on the classpath. Running a phase runs all the phases before it. - Follow-up: "Why
NoClassDefFoundErrorfrom a jar that compiled?" The jar did not contain its dependencies (article 23).
Practice questions
#Exercise 1
- Explain
==versusequalsand give a case where==surprises you. - Why must a
HashMapkey be effectively immutable? - What happens when you resize a
HashMap, and why? - Why can
list.remove(i)inside a for-each loop fail? - What is the difference between
Runnable,CallableandSupplier? - When would you use
ConcurrentHashMap.merge? - Explain how you would find the cause of a hung application.
Sample answers
==compares references for objects,equalscompares content as the class defines it.new String("a") == "a"isfalse, and boxedIntegervalues beyond the small cache differ.- If the key changes after insertion, its hash code changes, so the entry sits in the wrong bucket and cannot be found.
- The table doubles and entries are redistributed by their hash, to keep chains short. It is O(n), amortised over many inserts.
- The iterator detects a structural change and throws
ConcurrentModificationException. UseIterator.removeorremoveIf. Runnablereturns nothing and cannot throw checked exceptions,Callablereturns a value and may throw,Supplierreturns a value with no input and no checked exception.- To count or combine values atomically across threads, for example word counts, instead of get-then-put.
- 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
#- Next: Interview Concepts, Part 2: SQL, Spring, Backend, and the Job-Ready Checklist.
- To practise: re-run the programs in the linked articles and change them.
Sources & further reading
- Technology
- Software Engineering
- Career
- #collections
- #concurrency
- #core Java
- #interview questions
- #Java
- #Java backend
- #Java basics
- #Java interview
- #JPA
- #JVM
- #learn Java
- #Spring Boot
- #SQL
Connected lessons
References
- Strings, StringBuilder, Text Blocks and Time
- Project 3: The Job Application Tracker API, Assembled and Reviewed
- Null and Optional
Show all 24 →
- How the JVM Runs Your Code: Memory, GC and JIT
- Executors, Futures, Concurrent Collections and Virtual Threads
- Debugging: Errors, Stack Traces, the Debugger and Logging
- Classes, Objects and Encapsulation
- equals, hashCode, toString and the Object Contract
- Concurrency Fundamentals: Threads, Races and Synchronisation
- Ordering, Queues and Choosing a Collection
- Lambdas, Functional Interfaces and Method References
- Maps and How HashMap Works
- Streams in Practice (and When Not to Use Them)
- Java Interview Concepts, Part 2: SQL, Spring, JPA, Security, Testing and the Job-Ready Checklist
- Start Here: What Java Is, How It Runs and Your Roadmap
- Decisions, Loops, Methods and Scope
- Inheritance, Overriding and Overloading
- Variables, Types, Operators and Arrays
- Exceptions: Handling Errors Properly
- Generics: Type Safety, Wildcards and Erasure
- Enums, Records and Sealed Types
- Lists and Sets
- File I/O and Serialization
- Maven: What It Does and How to Use It
Linked from 1 guide
Other pages in the library that point here.
Keep reading
More in Technology →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

