Skip to content

Medium Java Interview Questions

94 medium questions with answers. Applied questions that check whether you can use the concepts on real work.

Topics in the medium set

OOP in Java: 15 Multithreading and Concurrency: 13 Strings and Exception Handling: 12 Collections Framework: 12 Java 8+ Features and Streams: 11 JDBC, Hibernate and JPA: 11 Java Basics and JVM: 10 Spring Boot and Microservices: 10
Solved — mediumStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Explain the main memory areas of the JVM.

Save to ▾
Show answer
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
02

What is garbage collection and how does the JVM decide an object is garbage?

Save to ▾
Show answer
Garbage collection automatically frees memory used by objects that are no longer reachable. The JVM starts from GC roots such as local variables on thread stacks, static fields and active threads, and marks every object reachable from them. Anything not marked is garbage. Because reachability is used rather than reference counting, circular references between unreachable objects are still collected.
03

What is the role of the JIT compiler?

Save to ▾
Show answer
The JVM first interprets bytecode, then profiles which methods run often. The Just In Time compiler converts these hot methods into optimised native code at runtime. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation and C2 applies aggressive optimisations like inlining and escape analysis. This is why Java apps get faster after a warm-up period.
04

What is autoboxing and what pitfall can it cause?

Save to ▾
Show answer
Autoboxing is automatic conversion between a primitive and its wrapper, such as int to Integer, and unboxing is the reverse. A common pitfall is a NullPointerException when unboxing a null Integer. Another is comparing Integer objects with ==, which works only for cached values from -128 to 127. Boxing inside tight loops also creates extra garbage and slows code.
05

What is a ClassLoader and what is the delegation model?

Save to ▾
Show answer
A ClassLoader loads .class files into the JVM. The main loaders are Bootstrap (core classes), Platform (formerly Extension) and Application (classpath). In the parent delegation model a loader first asks its parent to load a class and only loads it itself if the parent cannot. This prevents user code from replacing core classes like java.lang.String.
06

An application gets StackOverflowError in a recursive method. What do you do?

Save to ▾
Show answer
StackOverflowError means the thread stack is full, usually because recursion has no proper base case or the input is very deep. First check the base case and the recursive step with the failing input. If recursion is correct but deep, such as walking a long linked structure, convert it to an iterative solution with an explicit stack. Raising -Xss is only a temporary workaround.
07

A team member compares two Integer values with == and the check fails only for large numbers. Explain.

Save to ▾
Show answer
Integer.valueOf caches objects for values from -128 to 127, so autoboxed small numbers share the same object and == returns true. Larger values create new Integer objects, so == compares two different references and returns false. The fix is to use equals() or compare unboxed int values. Static analysis tools like SonarQube flag this pattern.
08

Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?

Save to ▾
Show answer
A typical command is: java -Xms4g -Xmx4g \ -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \ -XX:+HeapDumpOnOutOfMemoryError \ -XX:HeapDumpPath=/var/log/app \ -Xlog:gc*:file=/var/log/app/gc.log \ -jar app.jar In containers prefer -XX:MaxRAMPercentage=75 so the heap follows the container memory limit.
09

How do you take a thread dump and a heap dump of a running Java process?

Save to ▾
Show answer
Find the process id with jps or ps, then use jcmd, which is the recommended tool. jps -l jcmd <pid> Thread.print > threads.txt jcmd <pid> GC.heap_dump /tmp/heap.hprof Older tools jstack and jmap do the same. Take three thread dumps a few seconds apart to spot stuck threads, and analyse heap dumps in Eclipse MAT.
10

Tell me about a time you found and fixed a difficult production bug in a Java application.

Save to ▾
Show answer
Situation: our order service crashed with OutOfMemoryError every few days. Task: find the root cause without long downtime. Action: I enabled heap dumps on OOM, analysed the dump in Eclipse MAT and found a static HashMap used as a cache that was never cleared. I replaced it with a bounded Caffeine cache with expiry and added a heap usage alert. Result: no crashes in six months and memory stayed flat.
11

What is the difference between an abstract class and an interface in modern Java?

Save to ▾
Show answer
An abstract class can have state (instance fields), constructors and any access modifier, and a class can extend only one. An interface has no instance state but, since Java 8, can have default and static methods, and since Java 9 private methods; a class can implement many. Use an interface for a capability contract and an abstract class to share code and state among closely related classes.
12

What is the contract between equals() and hashCode()?

Save to ▾
Show answer
If two objects are equal by equals(), they must return the same hashCode(). Unequal objects may share a hash code, but fewer collisions give better performance. If you override equals() but not hashCode(), HashMap and HashSet break: an equal key lands in a different bucket and cannot be found. Use the same fields in both methods, or use records, which generate both.
13

How do you make a class immutable in Java?

Save to ▾
Show answer
Declare the class final, make all fields private and final, set them only in the constructor, and provide no setters. For mutable fields like a List or Date, make defensive copies in the constructor and in getters, or use List.copyOf. Immutable objects are thread safe and make good map keys. Java records give a concise way to create shallowly immutable data classes.
14

What is the difference between composition and inheritance, and which should you prefer?

Save to ▾
Show answer
Inheritance is an is-a relation where the subclass reuses parent code, but it creates tight coupling and fragile hierarchies. Composition is a has-a relation where a class holds another object and delegates work, such as a Car having an Engine. Prefer composition because it is flexible, allows changing behaviour at runtime and is easier to test. Use inheritance only for a true is-a relationship.
15

Explain the SOLID principles briefly.

Save to ▾
Show answer
Single Responsibility: a class has one reason to change. Open/Closed: open for extension, closed for modification. Liskov Substitution: subclasses must work wherever the parent is expected. Interface Segregation: prefer small, focused interfaces. Dependency Inversion: depend on abstractions, not concrete classes. Spring dependency injection is a practical example of dependency inversion.
16

What are records in Java and when should you use them?

Save to ▾
Show answer
Records, final in Java 16, are concise classes for immutable data. record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors, equals(), hashCode() and toString(). You can add validation in a compact constructor and add methods. Use them for DTOs, API responses and map keys. They cannot extend another class and are not suited to JPA entities, which need mutability.
17

What is the difference between static and dynamic binding?

Save to ▾
Show answer
Static binding is resolved at compile time and applies to private, static and final methods and to overloaded methods, because the compiler knows exactly which method to call. Dynamic binding is resolved at runtime based on the actual object type and applies to overridden instance methods. Static methods are hidden, not overridden, so the reference type decides which one runs.
18

You need to add a new payment method to a system that has a big if-else on payment type. How would you redesign it?

Save to ▾
Show answer
This breaks the Open/Closed principle. I would create a PaymentProcessor interface with a pay() method and one implementation per type, such as UpiProcessor and CardProcessor. A factory or a Spring map of beans keyed by type picks the right one. Adding a new method then means adding one new class without touching existing tested code, and each processor can be unit tested alone.
19

Objects used as HashMap keys cannot be found after insertion. What could be wrong?

Save to ▾
Show answer
Most likely the class overrides equals() but not hashCode(), or neither, so equal keys land in different buckets. Another cause is a mutable key: a field used in hashCode() was changed after insertion, so the lookup goes to a different bucket. The fix is to implement both methods on the same fields and use immutable keys such as String, records or final classes.
20

A getter returns an internal List and callers modify it, causing bugs. How do you fix this?

Save to ▾
Show answer
This breaks encapsulation. Return an unmodifiable view with Collections.unmodifiableList(list) or a copy with List.copyOf(list), so callers cannot change internal state. Also copy the list passed into the constructor or setter. If the class should be fully immutable, store List.copyOf in a final field. Expose specific methods like addItem() when controlled changes are needed.
21

Write a thread safe singleton class in Java.

Save to ▾
Show answer
The simplest safe options are an enum or the holder idiom. public class Config { private Config() {} private static class Holder { static final Config INSTANCE = new Config(); } public static Config getInstance() { return Holder.INSTANCE; } } The JVM loads Holder lazily and class initialisation is thread safe. An enum singleton also resists reflection and serialization attacks.
22

Implement equals() and hashCode() for an Employee class with id and email.

Save to ▾
Show answer
Use the same fields in both methods. @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Employee e)) return false; return id == e.id && Objects.equals(email, e.email); } @Override public int hashCode() { return Objects.hash(id, email); } Pattern matching for instanceof (Java 16) avoids an explicit cast.
23

Implement the Builder pattern for a User class with many optional fields.

Save to ▾
Show answer
A builder avoids long constructors. public class User { private final String name; private final int age; private User(Builder b) { name = b.name; age = b.age; } public static class Builder { private String name; private int age; public Builder name(String n) { name = n; return this; } public Builder age(int a) { age = a; return this; } public User build() { return new User(this); } } } Usage: new User.Builder().name("Asha").age(25).build(). Lombok @Builder generates this.
24

Write a record with validation in its compact constructor.

Save to ▾
Show answer
A compact constructor runs before fields are assigned. public record Money(String currency, long paise) { public Money { Objects.requireNonNull(currency); if (paise < 0) { throw new IllegalArgumentException("negative amount"); } } public Money add(Money o) { return new Money(currency, paise + o.paise); } } Storing money in paise as long avoids floating point errors.
25

Describe a time you improved the design of existing code.

Save to ▾
Show answer
Situation: our notification module used a 400 line class with switch cases for email, SMS and WhatsApp. Task: add push notifications without breaking anything. Action: I wrote tests for current behaviour, extracted a Notifier interface with one class per channel and used Spring to inject them by type. Result: push was added in one new class, bugs in that module dropped and new channels now take hours, not days.
26

Does the finally block always execute?

Save to ▾
Show answer
finally runs after try and catch in almost every case, including when the try block returns or throws. It does not run if the JVM exits through System.exit(), the process is killed or the thread dies abruptly. Avoid returning from finally, because that silently overrides the try block's return value and swallows exceptions.
27

How do you create a custom exception and when should you?

Save to ▾
Show answer
Extend RuntimeException for unchecked or Exception for checked, and provide constructors that accept a message and a cause so the root stack trace is kept. Create one when a domain error needs specific handling, such as InsufficientBalanceException, which a Spring @ControllerAdvice can map to an HTTP 422 response. Do not create exceptions for normal control flow.
28

What is exception chaining?

Save to ▾
Show answer
Exception chaining wraps a low level exception in a higher level one while keeping the original as the cause, for example throw new OrderException("save failed", sqlEx). The full stack trace shows both, with Caused by lines. It lets each layer speak its own language without losing the root cause, which is essential when debugging production logs.
29

Is it good practice to catch Exception or Throwable?

Save to ▾
Show answer
Usually no. Catching Throwable also catches Errors like OutOfMemoryError that the app cannot recover from, and catching Exception hides bugs by treating all failures the same. Catch the most specific exceptions you can handle. A broad catch is acceptable only at a top boundary, such as a global handler or thread entry point, where you log and return a safe error.
30

A log file shows a NullPointerException only for some users. How do you debug it?

Save to ▾
Show answer
Start with the stack trace; since Java 14 helpful NPE messages name exactly which variable was null. Reproduce with the failing user's data, which often has an optional field missing. Fix the root cause by validating input at the boundary, using Optional for values that may be absent and annotating with @NonNull. Add a unit test for that data case so it does not return.
31

Code builds a large CSV report with String += inside a loop and it is very slow. Why and what is the fix?

Save to ▾
Show answer
Each += creates a new String and copies all previous characters, so building n rows is O(n squared) in time and creates huge garbage. Use a single StringBuilder with append() inside the loop, ideally with an initial capacity, or write rows directly to a BufferedWriter for very large output. This turns minutes of work into milliseconds.
32

Exceptions are being swallowed with empty catch blocks in your codebase. How would you fix this?

Save to ▾
Show answer
Empty catches hide failures and make production issues invisible. I would find them with static analysis like SonarQube, then decide per case: handle the error properly, rethrow wrapped with context, or at least log with the stack trace. I would add a global exception handler for APIs and a team rule in code review and lint config to block new empty catch blocks.
33

Your REST API returns stack traces to clients when errors happen. How do you design proper error handling?

Save to ▾
Show answer
Never expose stack traces; they leak internals. In Spring Boot use a @RestControllerAdvice with @ExceptionHandler methods that map domain exceptions to status codes, such as 404 for not found and 400 for validation. Return a consistent body, ideally RFC 7807 ProblemDetail, with a code, message and trace id. Log full details on the server with the same trace id.
34

Write a custom unchecked exception and a Spring handler that returns HTTP 404.

Save to ▾
Show answer
Define the exception, then map it centrally. public class NotFoundException extends RuntimeException { public NotFoundException(String msg) { super(msg); } } @RestControllerAdvice public class ApiErrors { @ExceptionHandler(NotFoundException.class) public ProblemDetail notFound(NotFoundException e) { return ProblemDetail.forStatusAndDetail( HttpStatus.NOT_FOUND, e.getMessage()); } }
35

Find the first non-repeating character in a string.

Save to ▾
Show answer
Count in one pass, then scan again in order. public static char firstUnique(String s) { int[] cnt = new int[128]; for (char c : s.toCharArray()) cnt[c]++; for (char c : s.toCharArray()) { if (cnt[c] == 1) return c; } return '_'; } Two passes, O(n) time and O(1) extra space for ASCII input.
36

Read a large text file line by line efficiently and count lines containing ERROR.

Save to ▾
Show answer
Stream the file lazily so it never loads fully into memory. Path p = Path.of("app.log"); try (Stream<String> lines = Files.lines(p)) { long errors = lines .filter(l -> l.contains("ERROR")) .count(); System.out.println(errors); } try-with-resources closes the file handle. BufferedReader.readLine() in a loop is an equally good option.
37

Tell me about a time a production incident happened because of your code.

Save to ▾
Show answer
Situation: a release I made caused failed payments for some users. Task: restore service and find the cause fast. Action: I rolled back within ten minutes, then found I had not handled a null bank code from one partner, which threw an exception. I fixed it, added validation and a test with that partner's data and shared a short write-up. Result: no repeat and the team added null checks to our review checklist.
38

How does HashMap work internally?

Save to ▾
Show answer
HashMap stores entries in an array of buckets. It computes the key's hashCode(), spreads the bits and picks a bucket index. Collisions are stored as a linked list in the bucket, and since Java 8 a bucket with more than 8 entries (when the table has at least 64 buckets) becomes a red-black tree, making the worst case O(log n). When size passes capacity times load factor 0.75, it resizes to double.
39

What is the difference between HashMap and ConcurrentHashMap?

Save to ▾
Show answer
HashMap is not thread safe; concurrent writes can lose data or corrupt the structure. ConcurrentHashMap supports full concurrency: reads are lock free and writes use CAS or lock a single bin, so threads rarely block each other. It does not allow null keys or values. It also provides atomic compound operations such as computeIfAbsent and merge, which avoid check-then-act races.
40

What are fail-fast and fail-safe iterators?

Save to ▾
Show answer
Fail-fast iterators, used by ArrayList and HashMap, throw ConcurrentModificationException if the collection is structurally modified during iteration other than through the iterator itself; they check a modCount. Fail-safe or weakly consistent iterators, as in ConcurrentHashMap and CopyOnWriteArrayList, work on a snapshot or tolerate changes and never throw, but may not show the latest updates.
41

What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?

Save to ▾
Show answer
List.of() returns a truly immutable list; add, set and remove throw exceptions and nulls are not allowed. Arrays.asList() returns a fixed-size list backed by the array: set() works and writes through to the array, but add() and remove() throw. Collections.unmodifiableList() is a read-only view, so changes to the original list are still visible through it.
42

You need a cache that evicts the least recently used item when full. How would you build it in Java?

Save to ▾
Show answer
Extend LinkedHashMap with accessOrder set to true and override removeEldestEntry to return true when size exceeds capacity. Each get moves the entry to the end, so the eldest is the least recently used. It is not thread safe, so wrap it with synchronization for shared use. In production prefer Caffeine, which offers size and time based eviction with high concurrency.
43

A HashMap shared by many threads sometimes loses updates. How do you fix it?

Save to ▾
Show answer
HashMap is not thread safe, so concurrent put calls can overwrite each other. Replace it with ConcurrentHashMap and use atomic methods instead of get-then-put, for example counts.merge(key, 1, Integer::sum) or computeIfAbsent for lazy creation. Collections.synchronizedMap also works but locks the whole map, which hurts throughput under contention.
44

You have to process tasks in order of priority. Which collection do you use?

Save to ▾
Show answer
Use PriorityQueue, a binary heap where poll() always returns the smallest element by natural order or by a Comparator, such as Comparator.comparingInt(Task::priority). Insert and poll are O(log n) and peek is O(1). For multiple threads use PriorityBlockingQueue. Iterating a PriorityQueue does not give sorted order; only repeated poll() does.
45

An API needs to find the price band for any amount, for example the nearest lower slab. Which structure fits?

Save to ▾
Show answer
TreeMap is ideal because it keeps keys sorted and offers navigation methods. Store slab start amounts as keys and the band as value, then floorEntry(amount) returns the largest slab not above the amount in O(log n). ceilingKey, headMap and tailMap help with similar range queries such as tax slabs or delivery charges.
46

Implement an LRU cache using LinkedHashMap.

Save to ▾
Show answer
Access order plus removeEldestEntry gives LRU in a few lines. class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; LruCache(int capacity) { super(16, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > capacity; } } get and put are O(1).
47

Group a list of orders by city and sum the amount per city.

Save to ▾
Show answer
Use groupingBy with a summing collector. Map<String, Double> totals = orders.stream() .collect(Collectors.groupingBy( Order::city, TreeMap::new, Collectors.summingDouble(Order::amount))); TreeMap keeps cities sorted. For money, store amounts as long paise or BigDecimal and use Collectors.reducing with BigDecimal::add.
48

When would you choose ArrayDeque over Stack and LinkedList?

Save to ▾
Show answer
Stack is a legacy synchronized class built on Vector, so it is slow and exposes index methods that break stack rules. LinkedList allocates a node per element. ArrayDeque is a resizable circular array with no per-element allocation, so push, pop, offer and poll are fast amortised O(1). Use ArrayDeque for both stacks and queues in single-threaded code; it does not accept null.
49

Tell me about a time you improved performance by choosing a better data structure.

Save to ▾
Show answer
Situation: a report job matching 2 lakh transactions to customers took 40 minutes. Task: bring it under the 5 minute window. Action: profiling showed list.contains() inside a loop, which was O(n squared). I loaded customer ids into a HashSet and grouped transactions with a HashMap. Result: runtime dropped to 50 seconds and I shared the pattern in our team wiki.
50

What does the volatile keyword guarantee?

Save to ▾
Show answer
volatile guarantees visibility and ordering: a write to a volatile field is immediately visible to other threads, and it prevents reordering around that access under the Java Memory Model. It does not make compound operations like count++ atomic, because that is a read, modify and write. Use it for flags such as a stop signal, and use AtomicInteger or locks for counters.
51

What is the difference between synchronized and ReentrantLock?

Save to ▾
Show answer
synchronized is a built-in keyword that locks a monitor and releases it automatically at block exit. ReentrantLock is an explicit lock that adds tryLock with timeout, interruptible locking, fairness options and multiple Condition objects, but you must unlock in a finally block. Both are reentrant. Prefer synchronized for simple cases and ReentrantLock when you need its extra features.
52

What is a deadlock and how can it be prevented?

Save to ▾
Show answer
A deadlock happens when two or more threads each hold a lock and wait for a lock held by the other, so none can continue. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always acquiring locks in the same global order, using tryLock with a timeout, holding locks briefly and avoiding calls to unknown code while holding a lock.
53

What are virtual threads and when should you use them?

Save to ▾
Show answer
Virtual threads, final in Java 21, are lightweight threads managed by the JVM and mounted on a small pool of carrier OS threads. When one blocks on I/O, it unmounts so the carrier can run another. You can run millions of them, which suits thread-per-request servers doing lots of blocking calls. They do not speed up CPU-bound work, and you should not pool them.
54

How does ExecutorService work and why use a thread pool?

Save to ▾
Show answer
ExecutorService manages a pool of worker threads and a task queue. You submit Runnable or Callable tasks and get Futures, and workers reuse threads instead of creating one per task, which saves creation cost and limits concurrency. Configure core size, max size, queue and rejection policy through ThreadPoolExecutor. Always call shutdown() and awaitTermination() when done.
55

A counter shared between threads shows wrong totals. How do you fix it?

Save to ▾
Show answer
count++ is not atomic; two threads can read the same value and both write the same result, so updates are lost. Use AtomicInteger.incrementAndGet(), which uses CAS, or LongAdder for very high contention, as it spreads updates over cells. A synchronized method also works but is slower. volatile alone does not fix it because it gives visibility, not atomicity.
56

An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?

Save to ▾
Show answer
Since the calls are independent, run them in parallel with CompletableFuture.supplyAsync on a dedicated executor or with virtual threads, then join with allOf. Total latency becomes roughly the slowest call, about 300 ms. Add a timeout per call with orTimeout and a fallback for failures so one slow service does not block the whole response. Structured concurrency is another option in newer Java.
57

Implement a producer-consumer using BlockingQueue.

Save to ▾
Show answer
BlockingQueue handles waiting and signalling for you. BlockingQueue<Integer> q = new ArrayBlockingQueue<>(10); Runnable producer = () -> { for (int i = 0; i < 100; i++) { try { q.put(i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } }; Runnable consumer = () -> { try { while (true) System.out.println(q.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; put blocks when full and take blocks when empty.
58

Run two tasks in parallel with CompletableFuture and combine their results.

Save to ▾
Show answer
Use a dedicated executor for I/O work. ExecutorService pool = Executors.newFixedThreadPool(4); CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userApi.get(id), pool); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderApi.list(id), pool); Profile p = user.thenCombine(orders, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .join();
59

Print numbers 1 to 10 alternately from two threads (odd and even).

Save to ▾
Show answer
Use a shared lock with wait and notify. class Printer { int n = 1; synchronized void print(boolean odd) throws InterruptedException { while (n <= 10) { if ((n % 2 == 1) == odd) { System.out.println(Thread.currentThread().getName() + " " + n++); notifyAll(); } else wait(); } notifyAll(); } } Start one thread with print(true) and another with print(false).
60

Write code that runs 10,000 blocking tasks using virtual threads.

Save to ▾
Show answer
Use the virtual-thread-per-task executor in Java 21. try (var ex = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 10_000; i++) { int id = i; ex.submit(() -> { Thread.sleep(Duration.ofMillis(200)); return id; }); } } // close() waits for all tasks All tasks finish in about 200 ms because blocked virtual threads free their carriers.
61

Use CountDownLatch to wait for three worker threads to finish.

Save to ▾
Show answer
The main thread waits until the count reaches zero. CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { try { doWork(); } finally { latch.countDown(); } }).start(); } latch.await(30, TimeUnit.SECONDS); System.out.println("all done"); countDown in finally makes sure the latch is released even on error.
62

Describe a situation where you had to deliver under a tight deadline.

Save to ▾
Show answer
Situation: a bulk upload feature had to go live in four days for a client launch. Task: build it safely in time. Action: I split it into must-have and later items, used an ExecutorService to process rows in parallel, wrote focused tests for validation and kept the product owner updated daily. Result: we shipped on time, it handled 50,000 rows in under two minutes and we added the extras next sprint.
63

What is Optional and how should it be used?

Save to ▾
Show answer
Optional is a container that may or may not hold a value, used mainly as a method return type to show that a result can be absent, for example findById. Use map, filter, orElse, orElseGet and orElseThrow instead of calling get() blindly. Do not use Optional for fields, parameters or collections, and prefer orElseGet when the default is costly to create.
64

What does effectively final mean for lambdas?

Save to ▾
Show answer
A lambda can use a local variable from the enclosing method only if that variable is final or effectively final, meaning it is never reassigned after initialisation. Lambdas capture the value, not the variable, so this avoids confusing behaviour and races. To accumulate results, use a stream collector or an AtomicInteger instead of changing a captured local.
65

What is the difference between Collectors.toMap() and groupingBy()?

Save to ▾
Show answer
toMap() creates one entry per element using key and value functions and throws IllegalStateException on duplicate keys unless you give a merge function. groupingBy() collects all elements with the same key into a List by default, or applies a downstream collector like counting or summingInt. Use toMap for unique keys like id and groupingBy for categories like city.
66

A stream pipeline that updates a shared ArrayList in forEach gives random results with parallel(). Why?

Save to ▾
Show answer
ArrayList is not thread safe, and parallel streams run forEach on many threads, so additions race, get lost or throw exceptions. Side effects in streams are the problem. Replace forEach with collect(Collectors.toList()) or toList(), which handles merging per thread safely. Keep lambdas stateless and avoid modifying external state inside stream operations.
67

toMap() throws Duplicate key exception in production. How do you fix it?

Save to ▾
Show answer
The data has repeated keys that the developer assumed were unique. Decide the business rule, then pass a merge function, for example toMap(User::email, u -> u, (a, b) -> a) to keep the first, or use groupingBy if all values are needed. Also check upstream data quality, since duplicates may signal a deeper bug such as missing unique constraints.
68

Legacy code uses anonymous classes and loops everywhere. How would you modernise it safely?

Save to ▾
Show answer
First add tests around the behaviour. Then refactor in small steps: anonymous Comparators and Runnables become lambdas, simple loops that filter and transform become streams, and null checks around returns become Optional where useful. Keep complex loops with early exits as loops if a stream is less readable. Use IDE refactorings and review each change to avoid altering behaviour.
69

Using streams, find the employee with the highest salary in each department.

Save to ▾
Show answer
Group by department with a maxBy downstream collector. Map<String, Optional<Employee>> top = employees.stream() .collect(Collectors.groupingBy( Employee::department, Collectors.maxBy(Comparator.comparingInt(Employee::salary)))); To get values without Optional, wrap with collectingAndThen(maxBy(...), Optional::get), which is safe because each group has at least one element.
70

Write a sealed interface with records and a switch that computes area.

Save to ▾
Show answer
The switch needs no default because the type set is closed. sealed interface Shape permits Circle, Rect {} record Circle(double r) implements Shape {} record Rect(double w, double h) implements Shape {} static double area(Shape s) { return switch (s) { case Circle c -> Math.PI * c.r() * c.r(); case Rect(double w, double h) -> w * h; }; }
71

Flatten a list of lists of integers and compute the sum of squares of the even numbers.

Save to ▾
Show answer
flatMap then use a primitive stream to avoid boxing. int result = lists.stream() .flatMap(List::stream) .filter(n -> n % 2 == 0) .mapToInt(n -> n * n) .sum(); mapToInt returns an IntStream, whose sum() is simpler and faster than reduce on boxed Integers.
72

Tell me about a time you made a codebase more readable.

Save to ▾
Show answer
Situation: our reporting module had nested loops 200 lines long that new joiners feared. Task: make it maintainable without changing output. Action: I added snapshot tests on real report files, then refactored into small methods using streams, groupingBy and records for intermediate data, and reviewed each step with a teammate. Result: the module shrank by 40 percent and later changes took a day instead of a week.
73

Describe a time you had to learn a new technology quickly.

Save to ▾
Show answer
Situation: I joined a project using reactive Spring WebFlux with no prior experience. Task: contribute within two weeks. Action: I studied Project Reactor basics, built a small practice service, paired with a senior on my first ticket and kept notes on common operators. Result: I delivered my first feature in the second week and later wrote the team guide on avoiding blocking calls in reactive code.
74

What is the N+1 select problem in Hibernate and how do you fix it?

Save to ▾
Show answer
N+1 happens when you load N parent entities with one query and then a lazy association triggers one extra query per parent, giving N+1 queries. Fix it with a JOIN FETCH in JPQL, an @EntityGraph on the repository method, or batch fetching with @BatchSize or hibernate.default_batch_fetch_size. Detect it by enabling SQL logging or using a query count assertion in tests.
75

What is the difference between lazy and eager loading?

Save to ▾
Show answer
Lazy loading fetches an association only when it is first accessed, using a proxy; eager loading fetches it immediately with the parent. In JPA, @ManyToOne and @OneToOne default to EAGER, while @OneToMany and @ManyToMany default to LAZY. Best practice is to make all associations lazy and fetch what each use case needs with JOIN FETCH or entity graphs, which avoids loading huge object graphs.
76

Explain the entity lifecycle states in JPA.

Save to ▾
Show answer
Transient: a new object not yet linked to a persistence context. Managed (persistent): attached to the context, so changes are tracked and flushed automatically through dirty checking. Detached: was managed but the context closed or it was evicted; changes are not tracked until merge(). Removed: scheduled for deletion on flush. persist, merge, detach and remove move entities between these states.
77

An API listing 100 orders fires 101 SQL queries. How do you fix it?

Save to ▾
Show answer
This is the N+1 problem from a lazy association loaded in a loop or by JSON serialisation. Fetch what the endpoint needs in one query with JOIN FETCH or @EntityGraph(attributePaths = "items"), or use a DTO projection query. For collections with pagination, fetch ids first, then fetch associations in a second query to avoid in-memory paging. Add a test that asserts the query count.
78

Users get LazyInitializationException when the API returns an entity. What is happening?

Save to ▾
Show answer
The entity was loaded inside a transaction, the session closed, and then Jackson touched a lazy association outside it. Do not fix it by turning on open-session-in-view or making everything eager. Instead, map the entity to a DTO inside the service transaction and fetch needed associations explicitly with JOIN FETCH or an entity graph. Spring Boot logs a warning because open-in-view is on by default.
79

A query is fast in development but takes 8 seconds in production. How do you investigate?

Save to ▾
Show answer
Production has more data, so check the execution plan with EXPLAIN ANALYZE on production-like data. Look for full table scans, missing indexes on filter or join columns, functions on indexed columns and poor statistics. Check if Hibernate generates the SQL you expect. Add a suitable composite index, rewrite the query or paginate, and verify the plan improves before release.
80

Map a one-to-many relation between Order and OrderItem in JPA.

Save to ▾
Show answer
Make the child own the foreign key and keep both sides in sync. @Entity class Order { @Id @GeneratedValue Long id; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) List<OrderItem> items = new ArrayList<>(); void addItem(OrderItem i) { items.add(i); i.setOrder(this); } } @Entity class OrderItem { @Id @GeneratedValue Long id; @ManyToOne(fetch = FetchType.LAZY) Order order; }
81

Write a Spring Data JPA repository method that fetches orders with items to avoid N+1.

Save to ▾
Show answer
Use JOIN FETCH or an entity graph. public interface OrderRepository extends JpaRepository<Order, Long> { @Query("select distinct o from Order o join fetch o.items where o.customerId = :cid") List<Order> findWithItems(@Param("cid") Long customerId); @EntityGraph(attributePaths = "items") List<Order> findByStatus(String status); } Both load orders and items in one query.
82

Write a JDBC batch insert for a list of products.

Save to ▾
Show answer
Batching sends many rows in one round trip. String sql = "INSERT INTO product(name, price) VALUES (?, ?)"; try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { c.setAutoCommit(false); int n = 0; for (Product p : products) { ps.setString(1, p.name()); ps.setLong(2, p.price()); ps.addBatch(); if (++n % 500 == 0) ps.executeBatch(); } ps.executeBatch(); c.commit(); }
83

Tell me about a time you optimised a slow database query.

Save to ▾
Show answer
Situation: the customer search page took 6 seconds at peak. Task: bring it under 500 ms. Action: I captured the SQL, ran EXPLAIN ANALYZE and found a full scan due to LOWER(email) on an unindexed column and an N+1 on addresses. I added a functional index, fetched addresses with an entity graph and added pagination. Result: response time dropped to 180 ms and database CPU fell by a third.
84

How do you make sure database changes are released safely?

Save to ▾
Show answer
Situation: a manual schema change once broke our staging environment. Task: make migrations reliable. Action: I introduced Flyway with versioned scripts in the repo, required backward compatible changes such as adding nullable columns first, and ran migrations in CI against a test database. Result: we had zero failed migrations over the next year and rollbacks became predictable.
85

How does Spring Boot auto-configuration work?

Save to ▾
Show answer
At startup Spring Boot reads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each class uses conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so it creates beans only when the library is on the classpath and you have not defined your own. Run with --debug to see the condition report showing what was applied and why.
86

Explain bean scopes in Spring.

Save to ▾
Show answer
singleton is the default: one instance per application context. prototype creates a new instance each time it is requested. Web scopes include request, session and application. Singletons must be stateless or thread safe because all requests share them. Injecting a prototype into a singleton gives only one instance, so use ObjectProvider or a scoped proxy to get fresh ones.
87

What is Spring Boot Actuator used for?

Save to ▾
Show answer
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
88

A @Transactional method is not rolling back after an exception. What could be wrong?

Save to ▾
Show answer
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
89

You must expose configuration that differs between dev, QA and production. How do you manage it?

Save to ▾
Show answer
Use Spring profiles with application-dev.yml and application-prod.yml, and bind settings to typed @ConfigurationProperties classes with validation. Keep secrets out of the repo by injecting them through environment variables, Kubernetes Secrets or a vault. Activate the profile with SPRING_PROFILES_ACTIVE in each environment. Use the same build artefact everywhere and change only configuration.
90

Clients report duplicate orders when they retry after a timeout. How do you prevent it?

Save to ▾
Show answer
Make the create order API idempotent. The client sends an Idempotency-Key header; the server stores the key with the result in a table with a unique constraint or in Redis. A retry with the same key returns the saved response instead of creating a new order. Database unique constraints on business keys add another safety net.
91

Write a unit test for a service class using JUnit 5 and Mockito.

Save to ▾
Show answer
Mock the repository and verify behaviour. @ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock ProductRepository repo; @InjectMocks ProductService service; @Test void throwsWhenMissing() { when(repo.findById(1L)).thenReturn(Optional.empty()); assertThrows(NotFoundException.class, () -> service.get(1L)); verify(repo).findById(1L); } } No Spring context starts, so the test runs in milliseconds.
92

Bind typed configuration properties with validation in Spring Boot.

Save to ▾
Show answer
Use a record with @ConfigurationProperties. @ConfigurationProperties(prefix = "payment") @Validated public record PaymentProps( @NotBlank String baseUrl, @Min(100) int timeoutMs) {} // application.yml // payment: // base-url: https://pay.internal // timeout-ms: 2000 Enable it with @ConfigurationPropertiesScan on the main class. The app fails at startup if values are invalid.
93

Write a minimal Dockerfile for a Spring Boot application.

Save to ▾
Show answer
A multi-stage build keeps the image small. FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
94

How do you mentor junior developers on your team?

Save to ▾
Show answer
Situation: three freshers joined my Spring Boot team at once. Task: make them productive quickly. Action: I created a starter task list, paired with each on their first story, gave detailed but kind code reviews and held a weekly session on topics like transactions and testing. Result: all three shipped features independently within a month and one now mentors new joiners.

Frequently asked questions

Who should practise medium Java questions?

Anyone with some hands-on practice: most real interview time is spent on medium questions like these.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels