Java Core Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does
HashMapfind a value by key?Correct answer: It uses hashCode to pick a bucket, then equals to find the key in it
A good hashCode spreads keys across buckets. Long chains (since Java 8) turn into trees, but bad hash codes still slow things down.
2. You put an object into a
HashSet, then change a field used in itshashCode. What happens?Correct answer: The set may no longer find it, though it is still inside
The object stays in the old bucket. Keys of hash collections should be immutable, at least in the fields used by equals and hashCode.
3. What causes a
ConcurrentModificationExceptionhere?for (String s : list) { if (s.isEmpty()) list.remove(s); }Correct answer: Changing the list while a for-each loop iterates over it
The iterator is fail-fast. Use list.removeIf(String::isEmpty) or an explicit Iterator with remove().
4. What is the 'load factor' of a
HashMap?Correct answer: How full it may get before it resizes, 0.75 by default
When size exceeds capacity x load factor, the map doubles and rehashes. Setting the initial capacity avoids repeated resizing.
5. What does PECS mean for generic wildcards?
Correct answer: Producer extends, consumer super
Read from a List<? extends Number>, write into a List<? super Integer>. Collections.copy uses exactly this.
6. What is type erasure?
Correct answer: Generic types are removed at compile time, so
List<String>isListat runtimeThat's why you can't write new T() or check obj instanceof List<String>.
7. Why make a defensive copy of a list passed to a constructor?
Correct answer: So later changes to the caller's list don't change the object
Use List.copyOf(list) to store an unmodifiable copy. Records holding lists need this too.
8. Is a record with a
Listfield fully immutable?record Order(List<String> items) {}Correct answer: No: the field is final, but the list it points to can still change
Final only protects the reference. Copy in a compact constructor: items = List.copyOf(items).
9. What is the string pool?
Correct answer: A shared store of literals, so equal literals are one object
"a" == "a" is true because literals are pooled, while new String("a") is a separate object. Tests must still use equals.
10. What's a good practice when wrapping a low-level exception in your own?
Correct answer: Pass the original as the cause, so the stack trace is kept
new ServiceException("Failed to load", e) keeps 'Caused by:' in logs. Swallowing exceptions hides the real failure.
11. Which use of
Optionalis considered a misuse?Correct answer: Calling
get()unchecked or using Optional as a fieldget() on an empty Optional throws. Optional is for return values; fields and parameters should use null checks or overloads.
12. What is the difference between
orElseandorElseGet?Correct answer: orElse always evaluates its argument; orElseGet only when empty
orElse(createDefault()) calls createDefault even when a value exists. Use orElseGet for expensive defaults.
13. What does
flatMapdo in a stream?List.of(List.of(1, 2), List.of(3)).stream() .flatMap(List::stream) .toList();Correct answer: Flattens nested streams into one: [1, 2, 3]
map would give a stream of lists. flatMap turns each element into a stream and joins them.
14. What does this collector produce?
Stream.of("apple", "avocado", "banana") .collect(Collectors.groupingBy(s -> s.charAt(0)));Correct answer: A map {a=[apple, avocado], b=[banana]}
groupingBy builds a Map from the key function to lists of elements. Add a downstream collector like counting() to change values.
15. Why can parallel streams be a bad idea in a test framework or web server?
Correct answer: They use the shared ForkJoin pool and can starve other work
All parallel streams share the common pool. Blocking or heavy tasks there slow everything else in the JVM.
16. Why does a lambda need variables to be effectively final?
int count = 0; list.forEach(s -> count++);Correct answer: Lambdas capture values, so changing them doesn't compile
Use an AtomicInteger, a stream count() or a loop when you need to change state.
17. What is
String::toUpperCaseinmap(String::toUpperCase)?Correct answer: A method reference, short for
s -> s.toUpperCase()Method references point to existing methods: static, instance or constructor (ArrayList::new).
18. A class implements two interfaces with the same default method. What happens?
Correct answer: It must override the method to resolve the conflict
The compiler forces a choice. Inside, call a specific one with InterfaceA.super.method().
19. Why can a non-static inner class cause a memory leak?
Correct answer: It keeps a hidden reference to its outer object
A long-lived listener or task as an inner class keeps the whole outer object alive. Use static nested classes when you don't need the outer instance.
20. What does
protectedallow?Correct answer: Access from the same package and from subclasses
protected is wider than package-private: subclasses anywhere can use it.
21. What can an enum have besides constants?
Correct answer: Fields, constructors, methods and per-constant behavior
Enums are classes. EnumMap and EnumSet are fast collections for enum keys.
22. What does pattern matching for
instanceofsave you?if (obj instanceof String s) { System.out.println(s.length()); }Correct answer: The explicit cast after the type check
s is in scope only where the check succeeded. instanceof is false for null, so no NPE here.
23. What do sealed classes allow?
sealed interface Shape permits Circle, Square {}Correct answer: Restricting which classes may implement or extend a type
With sealed types, a switch over them can be exhaustive without a default branch.
24. What does a switch with type patterns over a sealed interface give you?
Correct answer: The compiler checks that each permitted subtype is handled
Add a new subtype and every switch that misses it fails to compile, a good guard against forgotten cases.
25. What does
volatileguarantee for a field?Correct answer: Writes become visible to other threads, but ++ isn't atomic
volatile fixes visibility, e.g. a stop flag. count++ on a volatile field can still lose updates.
26. What is a deadlock?
Correct answer: Two threads each wait for a lock the other holds
Take locks in a fixed global order or use tryLock with a timeout. A thread dump shows the cycle.
27. Why use an
ExecutorServiceinstead of creating threads by hand?Correct answer: It reuses a pool of threads and manages task queuing
Creating a thread per task is costly. Always shut the executor down, or the JVM may not exit.
28. What does
future.get()do on aFuture?Correct answer: Blocks until the result is ready, or throws if it failed
Use get(timeout, unit) so a stuck task doesn't hang the test or request forever.
29. What does
CompletableFuture.thenApplydo?Correct answer: Transforms the result once the future completes, without blocking
Async steps chain: thenApply, thenCompose, exceptionally. join() or get() blocks to read the result.
30. What is
AtomicIntegerfor?Correct answer: Lock-free atomic updates like incrementAndGet
It uses compare-and-set under the hood and is safe for counters shared by threads.
31. Why prefer
ConcurrentHashMapover aHashMapshared by threads?Correct answer: It's safe for concurrent use and doesn't lock the whole map
A shared HashMap can corrupt itself under concurrent writes. Methods like computeIfAbsent are atomic on ConcurrentHashMap.
32. What is
CountDownLatchuseful for in tests?Correct answer: Waiting until several threads have finished their work
Each worker calls countDown; the test calls await with a timeout. Better than Thread.sleep.
33. Why is
ThreadLocalpopular for WebDriver in parallel Selenium tests?Correct answer: Each thread gets its own driver, so tests don't share a browser
With a static driver, parallel tests click in each other's browsers. Remember to call remove() after each test.
34. Why must you call
ThreadLocal.remove()in thread pools?Correct answer: Pooled threads are reused, so old values leak into new tasks
Test runners and servers reuse threads. Stale drivers, users or tokens cause flaky and confusing failures.
35. What does
@ParameterizedTestwith@ValueSourcedo in JUnit 5?Correct answer: Runs the same test with each value as an argument
Other sources: @CsvSource, @MethodSource, @EnumSource. Each value shows as its own test in the report.
36. What does
assertAlldo in JUnit 5?Correct answer: Runs all grouped assertions and reports every failure
Useful for checking several fields of a response; you see all mismatches in one run.
37. How do you check that code throws an exception in JUnit 5?
var ex = assertThrows(IllegalArgumentException.class, () -> service.create(null));Correct answer:
assertThrows, which also returns the exception to inspectassertThrows checks type and lets you assert on the message. @Test(expected) was JUnit 4.
38. What is
@Tag("smoke")used for in JUnit 5?Correct answer: Selecting which tests run, e.g. only smoke tests in CI
Build tools filter by tags. @DisplayName sets readable names, @Disabled skips.
39. Why shouldn't tests depend on the order they run in?
Correct answer: Order isn't guaranteed, and parallel runs break hidden links
Each test should set up its own data. @TestMethodOrder exists but hides coupling.
40. What does
dependsOnMethodsdo in TestNG?Correct answer: Runs a test only after the listed tests passed; skips it otherwise
It's handy for setup flows but creates fragile chains. Prefer independent tests.
41. What is a TestNG
IRetryAnalyzerused for?Correct answer: Retrying failed tests a set number of times
Retries can hide flaky tests. Track retried tests and fix the root cause instead of raising the count.
42. How do TestNG listeners help in UI test projects?
Correct answer: They hook into events, e.g. take a screenshot when a test fails
ITestListener.onTestFailure is a common place for screenshots, logs and report attachments.
43. What does
when(repo.find(1)).thenReturn(user)do in Mockito?Correct answer: Stubs the mock to return
userwhenfind(1)is calledUnstubbed calls on a mock return defaults: null, 0, empty collections.
44. What does
verify(mailer).send(any())check?Correct answer: That
sendwas called on the mock with some argumentverify checks interactions. Add times(1) or never() to be precise.
45. What is an
ArgumentCaptorfor in Mockito?Correct answer: Capturing the argument passed to a mock to assert on it
E.g. capture the email object sent to the mailer and check its subject and recipient.
46. What's the difference between a mock and a spy in Mockito?
Correct answer: A spy wraps a real object and calls real methods unless stubbed
Spies are useful for partial stubbing, but often hint that the class does too much.
47. What does
<scope>test</scope>mean for a Maven dependency?Correct answer: It is available only for compiling and running tests
JUnit, Mockito and AssertJ use test scope so they don't end up in production artifacts.
48. Which Maven plugin runs unit tests in the
testphase?Correct answer: Surefire
Surefire runs unit tests; Failsafe runs integration tests in integration-test and verify, so failures don't stop cleanup.
49. What is the difference between the heap and the stack in the JVM?
Correct answer: Objects live on the heap; each thread's stack holds calls
Deep recursion fills the stack (StackOverflowError); too many objects fill the heap (OutOfMemoryError).
50. What usually causes a
StackOverflowError?Correct answer: Recursion that never ends or goes too deep
Each call adds a frame. A missing base case, or equals/toString calling each other, is a classic cause.
51. Why shouldn't you compare doubles with
==in tests?Correct answer: Floating-point math is approximate: 0.1 + 0.2 != 0.3
Use assertEquals(expected, actual, delta) or BigDecimal when exact decimal values matter.
52. Which type should be used for money amounts?
Correct answer:
BigDecimalBinary floats can't represent most decimal fractions exactly. Compare BigDecimals with compareTo, since equals also checks scale.
53. Why does
new BigDecimal("2.0").equals(new BigDecimal("2.00"))return false?Correct answer: equals compares value and scale; compareTo only value
A common test bug: assertEquals on BigDecimal fails for 2.0 vs 2.00. Use compareTo or AssertJ's isEqualByComparingTo.
54. Why inject a
Clockinstead of callingLocalDate.now()directly?Correct answer: Tests can fix the time and check date logic reliably
With Clock.fixed(...) a test about 'expires tomorrow' doesn't break at midnight.
55. What's the difference between
InstantandLocalDateTime?Correct answer: Instant is a point on the timeline; LocalDateTime has no time zone
Store timestamps as Instant. LocalDateTime is ambiguous around DST changes and across zones.
56. What does
staticinitialization order mean for this code?class Config { static final String URL = load(); static { System.out.println("init"); } }Correct answer: Static fields and blocks run once, in order, on first use of the class
Class init happens on first use. A failing static initializer gives ExceptionInInitializerError and NoClassDefFoundError later.
57. Why are mutable static fields risky in test code?
Correct answer: State leaks between tests and breaks parallel runs
A static WebDriver or test user shared by tests causes order-dependent and flaky failures.
58. What is the danger of catching
Exceptionin a test helper and returning null?Correct answer: The real failure is hidden, and the test fails later with NPE
Let exceptions propagate or rethrow with context. A clear failure at the source saves hours of debugging.
59. What does
Comparator.comparing(User::getAge).thenComparing(User::getName)give?Correct answer: Sort by age, then by name for equal ages
Comparators chain. reversed() flips an order. Good for checking sorting in UI or API tests.
60. What's wrong with
stream().peek(...)for side effects?Correct answer: It's for debugging and may skip some elements
With short-circuiting or some terminals, peek can be skipped. Use forEach for side effects.
61. What does
reducedo in a stream?Stream.of(1, 2, 3).reduce(0, Integer::sum);Correct answer: Combines elements into one value, here 6
reduce folds elements with an identity and an operation. For sums, mapToInt(...).sum() is clearer.
62. Why is
List.remove(1)on aList<Integer>confusing?Correct answer: It removes index 1, not the value 1
remove(int) wins overload resolution. Use remove(Integer.valueOf(1)) to remove the value.
63. What does
String.format("%.2f", 3.14159)return?Correct answer: "3.14"
Format uses the default locale: in Germany it gives "3,14". Tests that compare formatted numbers should set the locale.
64. Why may a test comparing formatted numbers pass locally but fail in CI?
Correct answer: The default locale differs, e.g. comma vs dot as decimal separator
Set Locale explicitly in the test or the code, e.g. String.format(Locale.ROOT, ...).
65. What is
OutOfMemoryError: Java heap spacea sign of?Correct answer: The heap is full: a leak or a heap too small for the load
Take a heap dump (-XX:+HeapDumpOnOutOfMemoryError) and look for what keeps objects alive.
66. Why are many tests failing with
NoClassDefFoundErrorafter a dependency upgrade?Correct answer: A class existed at compile time but is missing at runtime
Version conflicts on the classpath are typical. mvn dependency:tree shows which versions win.
67. What does
Objects.equals(a, b)add overa.equals(b)?Correct answer: It's null-safe: true if both are null, false if one is
a.equals(b) throws NPE when a is null. Objects.hash helps write hashCode the same way.
68. What does
@Nestedin JUnit 5 allow?Correct answer: Grouping related tests in inner classes with their own setup
Nested classes make 'given ... when ...' structure readable, with @BeforeEach per group.
69. How does JUnit 5 limit how long a test may run?
Correct answer: With
@TimeoutorassertTimeout@Test(timeout) was JUnit 4. A timeout keeps one hanging test from blocking the whole suite.
70. Why does a
HashMapiteration order look random?Correct answer: It depends on hash codes and capacity, not insertion order
Tests that assert on map order are flaky. Use LinkedHashMap or sort before comparing.
71. What does
Collections.unmodifiableList(list)return?Correct answer: A read-only view that still shows changes to the source
It's a view. List.copyOf makes an independent unmodifiable copy.
72. What happens in this code at runtime?
Object o = "text"; Integer n = (Integer) o;Correct answer: A ClassCastException is thrown
The compiler allows the cast from Object. The runtime check fails. Pattern matching instanceof avoids this.
73. What is the difference between
ErrorandException?Correct answer: Errors are serious JVM problems apps usually shouldn't catch
OutOfMemoryError and StackOverflowError are Errors. Catching Throwable broadly hides them.
74. Why can
Thread.sleep(2000)in a test be a bad wait?Correct answer: It is slow when things are fast and flaky when they are slower
Fixed sleeps either waste time or fail on a slow CI machine. Wait for a condition with a timeout, e.g. Awaitility or explicit waits.
75. What does
@BeforeAllneed in JUnit 5 by default?Correct answer: It must be static, unless the class uses PER_CLASS lifecycle
With @TestInstance(Lifecycle.PER_CLASS), one instance serves all tests and @BeforeAll can be non-static.