Skip to main content

Java Interview Questions for 2 to 3 Years Experience (2026): 31 Scenario Questions with Runnable Answers

31 scenario-based Java interview questions for 2 to 3 years of experience: core Java, collections and streams, concurrency, Spring Boot 4, REST, JPA and SQL. Every answer has real code and real output from a companion repository.

At two to three years of experience, interviewers stop asking you to define polymorphism. They describe something that went wrong in production — a counter that came out low, a transaction that never started, a query that ran six times — and ask you to explain it. This page collects 31 of those scenarios across core Java, collections and streams, concurrency, Spring Boot, REST, JPA and SQL. Every scenario is a collapsed answer. Open it and you get the sentence you can say out loud, then the real code and the real output from a companion project that was compiled and run for this article. Nothing below is quoted from memory; where a claim comes from the Java Language Specification or the Spring documentation instead of a run, the text says so. One idea runs through all 31 and it is worth planting now: Java and Spring do exactly what the code says, not what the author meant. Two equal objects land in different hash buckets because nobody asked for hashCode(). A transaction does not start because the call never went through the object that starts transactions. A LEFT JOIN quietly becomes an inner join because of where a filter was written. When you can say “here is the gap between what I assumed and what the system did”, you are answering at the right level. New to Java interviews? Start with the fifty fresher questions. Aiming higher? The five-year experience post reproduces eight production bugs in depth. This page sits between the two.
Versions tested. JDK 25.0.5.1+2 (Temurin, LTS), Spring Boot 4.2.0 (published to Maven Central on 2026-11-19; Spring Framework 7.1.0, Spring Data JPA 4.2.0), Hibernate ORM 7.4.15.Final, H2 2.5.252, JUnit 6.1.3, Maven 3.9.11. Versions were read from maven-metadata.xml and mvn dependency:list, not from release blogs. Companion code: java-interview-lab / experienced-2-3y.

How to answer a “what happens when…” question

Use the same three beats every time: what happens (the observable behaviour), why (the rule underneath), and the fix (what you would write instead). Interviewers at this level are listening for the second beat. “Use merge()” is a fix; “because check-then-put is two calls and the map only protects each call” is understanding. Each answer below follows that order, and each is backed by a test in the companion project that asserts the same lines you see here and writes them to a file. You can run all of it with mvn test on JDK 25.

Core Java: the compiler and runtime do exactly what you wrote

These six are the ones interviewers use to see whether you have been bitten by the language before.
Q1. A HashSet contains two objects that are equal. What went wrong? Say this: the class overrides equals() but not hashCode(). A HashSet uses the hash code to pick a bucket first and only calls equals() on objects in the same bucket. Without its own hashCode(), each object uses the identity hash from Object, so two equal objects almost always land in different buckets and equals() is never asked. The fix is to override both together, or use a record, which generates both.

Code: CoreQa.java

static final class BrokenPoint {
    final int x, y;
    BrokenPoint(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        return o instanceof BrokenPoint p && p.x == x && p.y == y;
    }
    // hashCode() deliberately NOT overridden
}

record GoodPoint(int x, int y) {}

Output: 01-core-java.txt

equal points in HashSet (equals only): size = 2
equal points in HashSet (record):      size = 1
Going deeper: the equals/hashCode contract and the bugs it causes, and how HashMap uses the hash.
Q2. A NullPointerException on a line with no obvious null. Where is it? Say this: autoboxing hides method calls. int n = map.get(key) calls intValue() on whatever get returned, and a missing key returns null. The ternary is the sneakier version: if one branch is Integer and the other is the primitive int, the whole expression has type int, so the Integer is unboxed even when you pick it and it is null. That rule is in JLS 15.25. Fixes: getOrDefault, or make both branches Integer.

Code: CoreQa.java (excerpt)

int n = stock.get("pencil");
Integer r = useDefault ? maybe : 0;
Integer safe = useDefault ? maybe : Integer.valueOf(0);

Output: 01-core-java.txt

int n = map.get("pencil") -> NullPointerException
useDefault ? maybe : 0   -> NullPointerException (type of ?: is int)
useDefault ? maybe : Integer.valueOf(0) -> null
map.getOrDefault("pencil", 0) -> 0
Note the third line: the “safe” ternary stops the crash but hands you a null Integer. Decide whether null is a legal value there; the crash was at least honest.
Q3. A subclass field is null inside a method the parent constructor called. Why? Say this: a parent constructor runs before the child’s field initialisers and constructor body. If the parent constructor calls an overridable method, the child’s override runs on a half-built object. So: never call overridable methods from a constructor. This one cost a correction while building the demo. I expected both fields to print null. The first run printed child for the field declared private final String constantLabel = "child", because a final variable of type String initialised with a constant expression is a constant variable (JLS 4.12.4) and the compiler inlines it. The field assigned in the constructor shows the real half-built state. So the trap exists, but a literal-initialised final will hide it.

Code: CoreQa.java

static class Base {
    Base() { describe(); }
    void describe() { System.out.println("Base.describe"); }
}

static class Child extends Base {
    private final String constantLabel = "child";        // a constant variable: the compiler inlines it
    private final String label;                          // assigned in the constructor, after super()
    Child() { super(); this.label = "child"; }
    @Override void describe() {
        System.out.println("Child.describe sees constantLabel = " + constantLabel + ", label = " + label);
    }
}

Output: 01-core-java.txt (first line is from inside the constructor, second from a call afterwards)

Child.describe sees constantLabel = child, label = null
Child.describe sees constantLabel = child, label = child
Q4. Someone changed a list you thought was private. How do you prevent that? Say this: a final field stops reassignment, not mutation. If a constructor stores the caller’s list, the caller can keep changing it; if a getter returns the stored list, every caller can change it. Take a defensive copy on the way in. List.copyOf in a record’s compact constructor does it in one line and the copy rejects add.

Code: CoreQa.java

static final class LeakyRoster {
    private final List<String> members;
    LeakyRoster(List<String> members) { this.members = members; }
    List<String> members() { return members; }
}

record SafeRoster(List<String> members) {
    SafeRoster { members = List.copyOf(members); }
}

Output: 01-core-java.txt

leaky roster after outside changes: [Asha, Ravi, Intruder, Another]
safe roster after outside change:   [Asha, Ravi]
safe roster add -> UnsupportedOperationException
Going deeper: records, compact constructors and immutability.
Q5. The log says “invalid port configuration” but not why. What do you change? Say this: you caught one exception and threw another without passing the original along, so the root cause is gone. Pass the caught exception as the cause. Stack traces then print a Caused by: chain and getCause() works for callers.

Code: CoreQa.java (excerpt)

static void loadLosingCause(String raw) {
    try {
        parsePort(raw);
    } catch (NumberFormatException e) {
        throw new IllegalStateException("invalid port configuration");
    }
}
// ...
throw new IllegalStateException("invalid port configuration", e);

Output: 01-core-java.txt

without cause: invalid port configuration | cause = null
with cause:    invalid port configuration | cause = java.lang.NumberFormatException: For input string: "80a"
Going deeper: checked vs unchecked exceptions, suppression and cost.
Q6. How do you make the compiler tell you when someone adds a new payment type? Say this: model the closed set with a sealed interface and record implementations, then handle them with a pattern-matching switch that has no default. Because the compiler knows every permitted subtype, a new subtype turns every incomplete switch into a compile error instead of a runtime surprise.

Code: CoreQa.java

sealed interface Payment permits Card, Upi, Cod {}
record Card(String last4) implements Payment {}
record Upi(String vpa) implements Payment {}
record Cod() implements Payment {}

static String describe(Payment p) {
    return switch (p) {
        case Card c -> "card ending " + c.last4();
        case Upi u -> "UPI " + u.vpa();
        case Cod c -> "cash on delivery";
    };
}

Output: 01-core-java.txt

Card[last4=4242] -> card ending 4242
Upi[vpa=asha@bank] -> UPI asha@bank
Cod[] -> cash on delivery
Now the proof that the compiler enforces it. This file is kept outside the Maven build and compiled on its own, with the switch missing the Cod case: NonExhaustiveSwitch.java.
        return switch (p) {
            case Card c -> "card " + c.last4();
            case Upi u -> "UPI " + u.vpa();
        };

javac’s own message, captured in 08-compile-errors.txt:

NonExhaustiveSwitch.java:9: error: the switch expression does not cover all possible input values
        return switch (p) {
               ^
1 error
Going deeper: sealed types and exhaustive switch, pattern matching in switch.

Collections and streams: small API choices change the result

None of these crash. They return a plausible wrong answer, which is why interviewers like them.
Q7. You added three words to a TreeSet and it holds two. Where did one go? Say this: a TreeSet decides whether two elements are the same by asking the comparator, not equals(). A comparator that only looks at length returns 0 for “apple” and “grape”, so the second is treated as a duplicate and silently ignored. Add a tie-breaker so the comparator is consistent with what you mean by “different”.

Code: CollectionsQa.java

TreeSet<String> byLength = new TreeSet<>(Comparator.comparingInt(String::length));
TreeSet<String> fixed = new TreeSet<>(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));

Output: 02-collections-streams.txt

TreeSet by length only: [fig, apple] (3 words added, size 2)
length then natural:    [fig, apple, grape]
Going deeper: Comparable vs Comparator.
Q8. list.remove(1) on a List<Integer> removed the wrong thing. Why? Say this: List has two overloads: remove(int index) and remove(Object o). A bare 1 is an int, so Java picks the index version. To remove the value, pass an Integer object.

Code: CollectionsQa.java (excerpt; the list starts as [10, 20, 30])

byIndex.remove(1);
byValue.remove(Integer.valueOf(10));

Output: 02-collections-streams.txt

remove(1)                  -> [10, 30]
remove(Integer.valueOf(10)) -> [20, 30]
Q9. Collectors.toMap throws IllegalStateException in production. Why only sometimes? Say this: toMap with two arguments treats a repeated key as an error. It works on test data with unique keys and fails the first time real data repeats one. Pass a merge function as the third argument to say how to combine, or use groupingBy when you want groups rather than one value per key.

Code: CollectionsQa.java (excerpt; the TreeMap only makes the printed order stable)

sales.stream().collect(Collectors.toMap(Sale::city, Sale::amount));
Map<String, Integer> merged = sales.stream()
    .collect(Collectors.toMap(Sale::city, Sale::amount, Integer::sum, java.util.TreeMap::new));

Output: 02-collections-streams.txt

toMap(city, amount) -> IllegalStateException: Duplicate key Pune (attempted merging values 100 and 250)
toMap with Integer::sum  -> {Mumbai=300, Pune=350}
groupingBy + counting    -> {Mumbai=1, Pune=2}
Q10. A peek() with a log line never prints. Is the stream broken? Say this: streams are lazy. Intermediate operations such as peek and filter only describe a pipeline; nothing runs until a terminal operation such as findFirst or collect is called. A short-circuiting terminal operation then stops as soon as it has its answer, so it may touch only a few elements.

Code: CollectionsQa.java (excerpt)

IntStream.rangeClosed(1, 10).boxed().peek(x -> touched.incrementAndGet()).filter(x -> x % 2 == 0);
// ...
Optional<Integer> first = IntStream.rangeClosed(1, 10).boxed()
    .peek(x -> touched.incrementAndGet()).filter(x -> x % 2 == 0).findFirst();

Output: 02-collections-streams.txt

no terminal operation: elements touched = 0
findFirst() on evens: result = 2, elements touched = 2
Ten numbers went in, two were touched: element 1 failed the filter, element 2 passed, and findFirst stopped.
Q11. orElse or orElseGet — and does it matter? Say this: it matters when the default is expensive or has side effects. The argument to orElse is evaluated before the call, whether or not the Optional has a value. orElseGet takes a supplier that only runs when the value is absent.

Code: CollectionsQa.java (excerpt; the Optional here always has a value)

cached.orElse(expensiveDefault());
cached.orElseGet(CollectionsQa::expensiveDefault);

Output: 02-collections-streams.txt

orElse(expensiveDefault())      -> default computed 1 time(s)
orElseGet(expensiveDefault)     -> default computed 0 time(s)
Going deeper: the complete Optional guide.
Q12. Sort employees by department, then by salary descending, with some departments null. Say this: chain comparators with thenComparing and wrap the nullable key in Comparator.nullsLast (or nullsFirst). Without the wrapper, a null department throws a NullPointerException inside the sort.

Code: CollectionsQa.java

staff.sort(Comparator.comparing(Employee::dept, Comparator.nullsLast(Comparator.naturalOrder()))
    .thenComparing(Employee::salary, Comparator.reverseOrder()));

Output: 02-collections-streams.txt

  Employee[name=Kiran, dept=Eng, salary=80000]
  Employee[name=Meera, dept=Sales, salary=120000]
  Employee[name=Asha, dept=Sales, salary=90000]
  Employee[name=Ravi, dept=null, salary=70000]

Concurrency: several threads, one wrong assumption

Both racy demos below lose updates only some of the time, so the tests run them up to 20 times and assert that a loss was seen at least once. The exact totals differ on every run, which is why the transcript records the verdict and not a number.
count++ is three steps, not one Thread A read 5 add 1 write 6 Thread B read 5 add 1 write 6 counter = 6 Both threads read 5 before either wrote. Two increments ran; the counter moved once. volatile makes every read and write visible to other threads. It does not glue the three steps into one. The same shape explains check-then-put on a ConcurrentHashMap: each call is safe, the sequence is not.
The picture is the argument for Q13 and Q15: visibility and atomicity are different guarantees, and a thread-safe method does not make a two-call sequence thread-safe.
Q13. The counter is volatile and still comes out low. Why? Say this: volatile guarantees that a write by one thread is visible to others and that reads and writes are not reordered across it. It does not make count++ atomic, because ++ is a read, an add and a write. Use AtomicInteger (or LongAdder under heavy contention), or a lock.

Code: ConcurrencyQa.java (excerpt)

static volatile int volatileCounter;
// ...
public static int volatileIncrements() throws InterruptedException {
    volatileCounter = 0;
    runThreads(8, () -> { for (int i = 0; i < 100_000; i++) volatileCounter++; });
    return volatileCounter;
}

Output: 03-concurrency.txt

volatile int, 8 threads x 100000 increments: LOST UPDATES (expected 800000)
AtomicInteger, same work:                    800000
Going deeper: the five-year post’s counter lab and 40 concurrency questions.
Q14. A task in your thread pool failed and nobody noticed. How? Say this: submit() captures any exception inside the returned Future. Nothing is printed and nothing is thrown until someone calls get(), which then wraps it in an ExecutionException. execute() has no Future, so the exception goes to the thread’s uncaught-exception handler. If you never call get() on a submitted task, its failure vanishes.

Code: ConcurrencyQa.java (excerpt)

t.setUncaughtExceptionHandler((th, ex) -> System.out.println("uncaught handler on " + th.getName() + ": " + ex.getMessage()));
// ...
Future<?> submitted = pool.submit(() -> { throw new IllegalStateException("boom from submit"); });
// ...
submitted.get();
// ...
pool.execute(() -> { try { throw new IllegalStateException("boom from execute"); } finally { seen.countDown(); } });

Output: 03-concurrency.txt

after submit(): no output yet, future.isDone() = true
future.get() -> ExecutionException, cause = java.lang.IllegalStateException: boom from submit
uncaught handler on worker: boom from execute
Going deeper: ExecutorService done right.
Q15. ConcurrentHashMap is thread-safe, yet a hit counter lost increments. Why? Say this: each method call on a ConcurrentHashMap is safe, but a sequence of calls is not one operation. containsKey, then get, then put leaves gaps in which another thread can write, exactly as in the diagram above. merge, compute and computeIfAbsent do the whole read-modify-write atomically for that key.

Code: ConcurrencyQa.java

public static int[] mapCounters() throws InterruptedException {
    ConcurrentHashMap<String, Integer> racy = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Integer> atomic = new ConcurrentHashMap<>();
    runThreads(8, () -> {
        for (int i = 0; i < 10_000; i++) {
            if (!racy.containsKey("hits")) racy.put("hits", 1); else racy.put("hits", racy.get("hits") + 1);
            atomic.merge("hits", 1, Integer::sum);
        }
    });
    return new int[] {racy.get("hits"), atomic.get("hits")};
}

Output: 03-concurrency.txt

containsKey/put/get sequence: LOST UPDATES (expected 80000)
merge(key, 1, Integer::sum):  80000
Going deeper: HashMap vs ConcurrentHashMap, the Javadoc.
Q16. When would you pick ReentrantLock over synchronized? Say this: when you need something synchronized cannot do. A thread waiting on a synchronized block waits until it gets the monitor; there is no timeout. ReentrantLock.tryLock(timeout, unit) lets a thread give up after a bounded wait and do something else. The price is that you must unlock() in a finally yourself.

Code: ConcurrencyQa.java (excerpt; another thread already holds the lock)

boolean got = lock.tryLock(50, TimeUnit.MILLISECONDS);

Output: 03-concurrency.txt

tryLock(50 ms) while another thread holds it -> false
tryLock() after the holder released it        -> true
Q17. Your service handles 10,000 slow I/O calls at once. Threads or virtual threads? Say this: for tasks that mostly wait (network, database, sleeps), virtual threads let you write ordinary blocking code with one thread per task, without a pool sized in the low hundreds. They do not make CPU-bound work faster. The demo starts 10,000 tasks that each sleep for 100 ms; they all run on virtual threads and finish well inside five seconds.

Code: ConcurrencyQa.java (excerpt)

try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        pool.submit(() -> {
            try { Thread.sleep(100); } catch (InterruptedException ignored) { }
            if (Thread.currentThread().isVirtual()) virtual.incrementAndGet();
            done.incrementAndGet();
        });
    }
}

Output: 03-concurrency.txt (the elapsed time is asserted, not printed, because it varies per machine)

tasks completed = 10000, ran on virtual threads = 10000
finished in under 5 seconds: true
Going deeper: from raw threads to virtual threads, diagnosing pinning.

Spring Boot: the object you call is often not the object you wrote

Here is the second planted idea paying off. Spring wraps many beans in a proxy: a stand-in object that adds behaviour (transactions, caching, security) around calls. If you hold the proxy, the behaviour happens. If you hold the raw object, it does not.
Only calls that arrive through the proxy get a transaction caller Spring proxyopens a transaction around@Transactional methods TxProbe objectinner()outerCallsInner() probe.inner() → proxy opens the transaction → transaction active = true probe.outerCallsInner() → passes through, nothing to open → this.inner() inside the object The inner call is made on the raw object, never touches the proxy, and transaction active = false. Same trap, same fix, for @Cacheable, @Async and @PreAuthorize: call through another bean.
The orange path is the whole question. The call into the object succeeds; the call inside the object is a plain Java method call that Spring never sees.
Q18. Why prefer constructor injection over field injection? Say this: with constructor injection the dependency is a final field, the object cannot exist without it, and the class can be built with plain new in a unit test, with no Spring context and no reflection. Field injection hides dependencies and needs the container (or reflection) to fill them.

Code: Invoice.java (excerpt) and SpringCoreScenariosTest.java (excerpt)

private final TaxPolicy tax;

public Invoice(TaxPolicy tax) { this.tax = tax; }
Invoice plain = new Invoice(amount -> 0.10);

Output: 04-spring-di-tx.txt

Invoice built with plain new and a lambda, no Spring context: total(100) = 110.0
Invoice from the context (FlatGst 18%):                       total(100) = 118.0
Q19. Two requests share data you thought was per-request. What is the scope? Say this: Spring beans are singletons by default: one object per application context, shared by every caller. State kept in a field of a singleton is shared across all requests, so request-specific data belongs in method parameters or a narrower scope. prototype scope creates a new object for every lookup.

Code: Counters.java

@Component
public static class SingletonCounter {
    private int count;
    public int next() { return ++count; }
}

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class PrototypeCounter {
    private int count;
    public int next() { return ++count; }
}

Output: 04-spring-di-tx.txt

two getBean(SingletonCounter) calls return the same object: true
caller A next() = 1, caller B next() = 2
two getBean(PrototypeCounter) calls return the same object: false
caller A next() = 1, caller B next() = 1
Caller B saw caller A’s increment. Because many threads call a singleton at once, mutable fields in it also need to be thread-safe — usually the better answer is not to have them.
Q20. @Transactional is on the method, but no transaction starts. Why? Say this: because the call was made on this. @Transactional is applied by the proxy (see the diagram above), and a method calling another method of the same object bypasses the proxy. The fix is to make the call through another bean, so the call enters through a proxy. The same trap breaks @Cacheable and @Async; the cache abstraction post shows it for caching.

Code: TxProbe.java

/** Not transactional itself; calls inner() on "this", which is the raw object, not the proxy. */
public boolean outerCallsInner() { return inner(); }

@Transactional
public boolean inner() { return TransactionSynchronizationManager.isActualTransactionActive(); }

Output: 04-spring-di-tx.txt

TxProbe injected as a Spring proxy: true
probe.inner()           -> transaction active = true
probe.outerCallsInner() -> transaction active = false
The same annotation, the same method, two answers; only the route into it differs. The fix (moving the called method to a second bean) is the documented standard advice from the Spring reference and was not run here. Going deeper: propagation, isolation and silent failures.
Q21. An IOException was thrown inside a transaction, yet the row was saved. Why? Say this: by default Spring rolls back on unchecked exceptions (RuntimeException and Error) and commits on checked ones, so a checked exception leaves the transaction to commit. To roll back on a checked exception, say so with rollbackFor.

Code: Transfers.java (excerpt)

@Transactional
public void failWithChecked(String name) throws IOException {
    customers.save(new Customer(name));
    throw new IOException("checked failure after save");
}

@Transactional(rollbackFor = Exception.class)
public void failWithCheckedRollbackFor(String name) throws IOException {
    customers.save(new Customer(name));
    throw new IOException("checked failure after save");
}

Output: 04-spring-di-tx.txt

RuntimeException after save           -> rows added = 0
checked IOException after save        -> rows added = 1
checked + rollbackFor = Exception.class -> rows added = 0

REST: status codes and error bodies are part of the contract

A client cannot read your code, so what it learns about a failure is the status code and the body. These three answers use Spring MVC with MockMvc inside a @SpringBootTest: the full application context, but no real HTTP server. The error bodies follow RFC 9457 problem details.
Q22. What should POST /customers return on success? Say this: 201 Created, a Location header pointing at the new resource, and usually the created representation in the body. 200 OK works but tells the client less.

Code: CustomerApi.java (excerpt)

@PostMapping
public ResponseEntity<CustomerView> create(@Valid @RequestBody CreateCustomer body) {
    Customer saved = customers.save(new Customer(body.name()));
    return ResponseEntity.created(URI.create("/customers/" + saved.getId()))
        .body(new CustomerView(saved.getId(), saved.getName()));
}

Output: 06-rest.txt

POST /customers {"name":"Asha"}
  status   = 201
  Location = /customers/1
  body     = {"id":1,"name":"Asha"}
Q23. How do you reject a one-character name, and what does the client see? Say this: put Bean Validation annotations on the request record and add @Valid on the controller parameter. A failed validation becomes 400 Bad Request before your method body runs. One observation from the run, not from the docs: with ApiErrors extending Spring’s ResponseEntityExceptionHandler and nothing more, the 400 body says Invalid request content. and does not name the failing field. A real API usually adds the field errors itself.

Code: CustomerApi.java (excerpt)

public record CreateCustomer(@NotBlank @Size(min = 2, max = 40) String name) {}

Output: 06-rest.txt

POST /customers {"name":"A"}   (@Size(min = 2))
  status = 400
  body   = {"detail":"Invalid request content.","status":400,"title":"Bad Request"}
Going deeper: Bean Validation in depth.
Q24. Where do you turn a “not found” exception into a 404 for every controller? Say this: in one @RestControllerAdvice class. Controllers throw a domain exception and the advice maps it to a ProblemDetail with the right status, so the mapping lives in one place instead of in every method.

Code: ApiErrors.java (excerpt)

public class ApiErrors extends ResponseEntityExceptionHandler {

    @ExceptionHandler(CustomerApi.CustomerNotFound.class)
    ProblemDetail notFound(CustomerApi.CustomerNotFound e) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        pd.setTitle("Customer not found");
        return pd;
    }

Output: 06-rest.txt

GET /customers/99
  status = 404
  body   = {"detail":"customer 99 not found","status":404,"title":"Customer not found"}
Going deeper: ProblemDetail and global exception handling in Spring Boot 4, and the broader Spring Boot 4 interview questions.

JPA: one innocent loop, six SQL statements

JPA questions at this level are almost always about how many queries ran and when the session was open. The demos count real SQL statements using Hibernate’s statistics, on data with five customers and twelve orders.
Lazy loop: 1 + 5 statements select … from customer select … from customer_order where customer_id = 1 … where customer_id = 2 … where customer_id = 3 … where customer_id = 4 … where customer_id = 5 JOIN FETCH or @EntityGraph: 1 statement select … from customerjoin customer_order on … The first plan’s statement count grows with the number of customers; the second stays at one.
The point of the picture: the loop looks identical in both cases. What changes is that in the left plan each access to getOrders() triggers its own query, so the cost scales with rows, not with the code you wrote.
Q25. A report that loops over customers and their orders is slow. What do you check first? Say this: the number of SQL statements. This is the N+1 problem: one query loads N customers, then touching each customer’s lazy orders collection runs one more query per customer. Fix it by loading the association in the same query, with JOIN FETCH in JPQL or an @EntityGraph on the repository method.

Code: OrderReports.java and CustomerRepository.java (excerpts)

@Transactional(readOnly = true)
public int sumNaive() {
    int sum = 0;
    for (Customer c : customers.findAll()) {
        for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
    }
    return sum;
}
@Query("select distinct c from Customer c join fetch c.orders")
List<Customer> findAllWithOrdersJoinFetch();

@EntityGraph(attributePaths = "orders")
List<Customer> findAllByOrderByIdAsc();

Output: 05-jpa.txt

data: 5 customers, 12 orders (4 customers x 3 orders, plus one customer with none)
lazy loop (default)        : total = 2400, SQL statements = 6
JOIN FETCH query           : total = 2400, SQL statements = 1
@EntityGraph("orders")     : total = 2400, SQL statements = 1
Same total, six statements versus one. Going deeper: catching N+1 in a test, lazy loading in Hibernate 7.
Q26. LazyInitializationException — what is it and how do you fix it properly? Say this: a lazy association is loaded on first access, and that needs an open Hibernate session. When the transaction (and session) have ended, the access fails. The proper fixes are to load what you need inside the transaction (fetch join, entity graph) or return a DTO built inside it. Switching on open-session-in-view hides the error by keeping the session open through the web layer; this project sets spring.jpa.open-in-view=false (Spring Boot’s default is true), which is why the failure is visible.

Code: OrderReports.java

/** No @Transactional: the session is closed when findAll() returns, so touching orders fails. */
public int sumWithoutTransaction() {
    int sum = 0;
    for (Customer c : customers.findAll()) {
        for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
    }
    return sum;
}

Output: 05-jpa.txt

no @Transactional around the loop -> LazyInitializationException
message: Cannot lazily initialize collection of role 'com.ankurm.interviewlab.exp23.spring.Customer.orders' with key '1' (no session)
Going deeper: proxies and LazyInitializationException.
Q27. You only need names and order totals. Do you load entities? Say this: no. Select exactly the columns you need into a DTO (a record here) with a constructor expression. It avoids loading collections at all. Use a LEFT JOIN so customers with no orders still appear, and coalesce to turn the missing sum into 0.

Code: CustomerRepository.java

@Query("select new com.ankurm.interviewlab.exp23.spring.CustomerRepository$OrderTotal(c.name, coalesce(sum(o.amount), 0)) "
     + "from Customer c left join c.orders o group by c.name order by c.name")
List<OrderTotal> totals();

Output: 05-jpa.txt

  OrderTotal[name=Asha, total=600]
  OrderTotal[name=Kiran, total=600]
  OrderTotal[name=Meera, total=600]
  OrderTotal[name=Nobody, total=0]
  OrderTotal[name=Ravi, total=600]
Going deeper: 40 Hibernate and JPA interview questions, Spring Data JPA guide.

SQL: ties, NULLs and the join you did not mean

These four run on H2 through JdbcClient. Standard SQL features used here (window functions, FETCH FIRST) are available in the major databases, but check your own database’s syntax before copying. The data: salaries of 120000, 120000, 90000, 80000 and 70000, where two people tie for the top.
Q28. Find the second highest salary. What breaks when two people tie? Say this: ORDER BY salary DESC with an offset of one skips one row, not one salary. With a tie at the top, the second row is the top salary again. Ask for distinct values, or use MAX below the maximum, or DENSE_RANK(), which gives tied rows the same rank without gaps.

Code: SqlScenariosTest.java (excerpt)

Object offsetNoDistinct = rows("SELECT salary FROM employee ORDER BY salary DESC OFFSET 1 ROW FETCH FIRST 1 ROW ONLY").get(0).get("SALARY");
Object sub = rows("SELECT MAX(salary) AS s FROM employee WHERE salary < (SELECT MAX(salary) FROM employee)").get(0).get("S");
Object dense = rows("SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM employee) WHERE r = 2").get(0).get("SALARY");

Output: 07-sql.txt

ORDER BY salary DESC OFFSET 1 (no DISTINCT) -> 120000   <- the tie makes this the top salary again
SELECT DISTINCT ... OFFSET 1                -> 90000
MAX(salary) WHERE salary < MAX(salary)      -> 90000
DENSE_RANK() = 2                            -> 90000
Q29. Find duplicate emails, then delete the extras but keep one of each. Say this: GROUP BY email HAVING COUNT(*) > 1 finds them. HAVING filters groups after grouping, whereas WHERE filters rows before. To delete, keep the lowest id per email and remove every row whose id is not that minimum. Run the SELECT version of the condition first, every time.

Code: SqlScenariosTest.java (excerpt)

rows("SELECT email, COUNT(*) AS n FROM signup GROUP BY email HAVING COUNT(*) > 1 ORDER BY email")
int deleted = jdbc.sql("DELETE FROM signup WHERE id NOT IN (SELECT MIN(id) FROM signup GROUP BY email)").update();

Output: 07-sql.txt

emails seen more than once:
  [email protected] x3
  [email protected] x2
DELETE ... NOT IN (SELECT MIN(id) ... GROUP BY email) removed 3 rows; left: [1, 2, 4]
Q30. A department with no employees vanished from the report. Why? Say this: an INNER JOIN keeps only rows with a match on both sides. A LEFT JOIN keeps every left row and fills the right side with NULLs when nothing matches. Two follow-up traps: COUNT(*) counts the NULL-extended row as 1 while COUNT(column) skips NULLs; and a WHERE condition on the right table throws the NULL rows away, turning the LEFT JOIN back into an inner join. Put that condition in ON instead.

Code: SqlScenariosTest.java (excerpt)

Map<String, Object> ops = rows("SELECT d.name, COUNT(*) AS star, COUNT(e.id) AS col FROM department d LEFT JOIN employee e ON e.dept_id = d.id WHERE d.id = 30 GROUP BY d.name").get(0);
long whereFilter = rows("SELECT d.name FROM department d LEFT JOIN employee e ON e.dept_id = d.id WHERE e.salary > 100000 GROUP BY d.name").size();
long onFilter = rows("SELECT d.name FROM department d LEFT JOIN employee e ON e.dept_id = d.id AND e.salary > 100000 GROUP BY d.name").size();

Output: 07-sql.txt

departments (id 30 'Ops' has no employees)
INNER JOIN departments returned: 2   LEFT JOIN: 3
Ops: COUNT(*) = 1, COUNT(e.id) = 0   <- COUNT(*) counts the NULL-extended row
LEFT JOIN + WHERE e.salary > 100000 keeps 2 departments; the same filter in ON keeps 3
Q31. A lookup by email is slow. What does an index change? Say this: without an index the database reads every row to find matches; with an index on the column it jumps to the matching entries. You prove it by reading the query plan, not by guessing. Plans and their wording differ between databases, so treat the H2 output below as an illustration of the idea, and run EXPLAIN on your own database before and after.

Code: SqlScenariosTest.java (excerpt; the table holds 20,000 rows)

exec("CREATE INDEX idx_big_email ON big_signup(email)");

Output: 07-sql.txt

without an index: SELECT     "PUBLIC"."BIG_SIGNUP"."ID",     "PUBLIC"."BIG_SIGNUP"."EMAIL" FROM "PUBLIC"."BIG_SIGNUP"     /* PUBLIC.BIG_SIGNUP.tableScan */ WHERE "EMAIL" = '[email protected]'
with idx_big_email: SELECT     "PUBLIC"."BIG_SIGNUP"."ID",     "PUBLIC"."BIG_SIGNUP"."EMAIL" FROM "PUBLIC"."BIG_SIGNUP"     /* PUBLIC.IDX_BIG_EMAIL: EMAIL = '[email protected]' */ WHERE "EMAIL" = '[email protected]'
Read the comment in the middle of each line: tableScan before, IDX_BIG_EMAIL: EMAIL = ... after.

Testing: what to say when they ask how you tested this

Interviewers often follow a scenario with “and how would you test that?” The companion project’s own tests are a compact set of answers.
Unit test, @SpringBootTest or MockMvc? Use the smallest test that can show the behaviour. Q18’s Invoice needs no Spring at all, so its test is a plain new. Q20 to Q27 are about what Spring and Hibernate do, so they need @SpringBootTest. The REST answers use MockMvc inside @SpringBootTest, which exercises the real controllers and the exception advice without opening a port. Each Spring test class in the project has its own in-memory database name and is marked @DirtiesContext so row counts in one class cannot leak into another; that was a design choice for stable counts, not something a failure forced. Test sources: JpaScenariosTest.java, RestScenariosTest.java.
How do you test a race condition? You cannot prove a race is absent by running code, but you can prove one is present. Q13 and Q15 run the racy version up to 20 times and assert that updates were lost at least once, and assert that the fixed version always reaches the exact total. Plain test source: PlainTranscriptsTest.java. For the JUnit and Mockito side of testing questions, see 30 JUnit 6 and Mockito interview questions.

Should you memorise this list?

No — run it and change one line. A memorised answer survives the first question and fails the follow-up (“and what if the keys are the same?”). The reliable way to own an answer is to break the demo yourself: remove the merge function, add the missing hashCode, move @Transactional to another bean, and watch the output change.

Limits to keep in mind: the SQL ran on H2, not your production database; Spring and Hibernate behaviour was observed on the versions listed at the top; and the statements attributed to the JLS, the Javadoc and the Spring reference were not executed here.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.