30 questions from every round of the set, in 40 minutes. This is practice: your answers are marked in your browser, and the score is yours alone.
30 questions · 40 minutes
Before you start
30 questions in 40 minutes. The clock starts when you press Start and does not pause.
You can change an answer until you submit. Nothing is marked before that.
When you submit, or when the time runs out, every question shows the right answer and its explanation.
No marks are taken off for a wrong answer.
Question 1 · medium
What does this Java 21 program print?
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d) + " " + c.equals(d));
}
}
Autoboxing calls Integer.valueOf, which returns cached objects for values from -128 to 127, so the two boxed 127s are the same object and == is true. 128 is outside the cache, so each boxing creates a new object and == compares two different references. Compare wrapper objects with equals (or unbox them), never with ==.
Question 2 · hard
This Java 21 code prints null instead of home. What is the bug?
static class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
}
// in main
Map<Point, String> places = new HashMap<>();
places.put(new Point(1, 2), "home");
System.out.println(places.get(new Point(1, 2)));
HashMap first uses hashCode to pick a bucket and only then calls equals on keys with the same hash. Without an override, hashCode comes from Object and differs for the two separate Point objects, so get looks in the wrong place and returns null. Whenever you override equals, override hashCode from the same fields, or declare the type as a record, which generates both.
Question 3 · medium
An interviewer asks about static and dynamic binding. Which of these is decided at compile time?
Overload resolution uses the declared types of the arguments, so the compiler fixes the choice; static and private methods cannot be overridden, so they are bound at compile time too. Overridden instance methods, including interface and default methods, are dispatched at runtime on the actual class of the object. This runtime dispatch is what makes polymorphism work.
Question 4 · easy
Which statement about abstract classes and interfaces in Java 21 is correct?
An abstract class is a partial class: it can hold state in instance fields and has constructors that subclasses call through super. An interface has no instance state (its fields are implicitly public static final), but since Java 8 it can carry default and static method bodies. A class extends at most one class but can implement many interfaces, which is why interfaces are used to describe capabilities.
Question 5 · medium
This Java 21 code prints false, although the list holds an equal point. What is the bug?
static class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
public boolean equals(Point p) { return p.x == x && p.y == y; }
@Override public int hashCode() { return 31 * x + y; }
}
// in main
List<Point> points = List.of(new Point(1, 2));
System.out.println(points.contains(new Point(1, 2)));
To override a method, the subclass must use the same parameter types; equals(Point) is a new overload, so Object.equals(Object) (reference comparison) is what contains calls. Writing @Override on it would have turned the mistake into a compile error. Always declare equals(Object o) and check the type inside it.
Question 6 · easy
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("banana", 2);
stock.put("apple", 5);
stock.put("cherry", 1);
System.out.println(stock);
}
}
A TreeMap keeps its keys sorted by their natural ordering (or by a Comparator you pass), whatever order you insert them in. Strings sort alphabetically, so apple comes first; the values play no part in the order. Use LinkedHashMap when you want insertion order instead.
Question 7 · easy
Which statement comparing ArrayList and LinkedList is correct?
ArrayList is backed by an array, so reading by index is a direct lookup, and appending is amortised O(1) because the array grows only occasionally. LinkedList stores a node with two links per element, which costs more memory and makes access by index a walk. Neither class is synchronized; ArrayList is the usual default.
Question 8 · easy
Which statement about checked and unchecked exceptions in Java is correct?
The compiler enforces the catch-or-declare rule only for checked exceptions: subclasses of Exception that are not subclasses of RuntimeException. Unchecked exceptions such as NullPointerException and IllegalArgumentException usually signal programming errors and need no throws clause. Checked exceptions model failures a caller can reasonably handle, such as a missing file.
Question 9 · hard
What does this Java 21 program print?
public class Main {
static int f() {
int x = 1;
try { return x; } finally { x = 2; }
}
static int g() {
try { return 1; } finally { return 2; }
}
public static void main(String[] args) {
System.out.println(f() + " " + g());
}
}
In f, the return value is evaluated and saved when return x runs, so changing the local x in finally afterwards does not alter it. In g, the return in finally replaces the pending return value, and it would also swallow any exception. That is why a return inside finally is considered a bug.
Question 10 · medium
What does this Java 21 program print?
public class Main {
static class Box { int v; Box(int v) { this.v = v; } }
static void change(Box b) { b.v = 10; b = new Box(20); b.v = 30; }
static void bump(int n) { n++; }
public static void main(String[] args) {
Box box = new Box(1);
int n = 1;
change(box);
bump(n);
System.out.println(box.v + " " + n);
}
}
Java is always pass-by-value; for an object the value passed is a copy of the reference. b.v = 10 changes the object that both references point to, but b = new Box(20) only repoints the method's own copy, so the caller never sees 30. The int is copied too, so n++ changes only the parameter.
Question 11 · medium
A method opens a BufferedReader on a file and reads a line, and the read may throw IOException. What is the recommended way to make sure the reader is always closed?
try-with-resources calls close() on every AutoCloseable it opened when the block ends, whether it ends normally or with an exception, and keeps the original exception with any failure from close() added as suppressed. A close() at the end of try is skipped when the read throws, and one only in catch is skipped when it does not. Garbage collection gives no guarantee about when, or whether, a file handle is released.
Question 12 · medium
Inside this method, where do age, the variable s and the Student object live?
void register() {
int age = 21;
Student s = new Student("Asha");
}
Local variables, whether primitives or references, live in the stack frame of the method call and disappear when the method returns. Objects created with new always live on the heap, and the local reference only points to them. Once no reference to the Student remains, it becomes eligible for garbage collection.
Question 13 · medium
What does this Java 21 program print?
public class Main {
static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(isAnagram("listen", "silent") + " " + isAnagram("aab", "abb"));
}
}
An int[26] counter adds one for each letter of the first string and subtracts one for each letter of the second; the strings are anagrams only if every count returns to zero. aab and abb use the same set of letters but in different amounts, so the count for a ends at 1 and the method returns false. Comparing only the sets of letters is the classic mistake this catches; the method is O(n) time and O(1) space for lowercase letters.
Question 14 · medium
This method should reverse a string in place in a char[]. reverse("abc") returns cba, but reverse("abcd") returns dbca. Which change fixes it?
static String reverse(String s) {
char[] c = s.toCharArray();
int n = c.length;
for (int i = 0; i <= n / 2; i++) {
char t = c[i];
c[i] = c[n - 1 - i];
c[n - 1 - i] = t;
}
return new String(c);
}
Each swap fixes two positions, so only the first half of the indices may drive the loop: i < n / 2. With i <= n / 2 and an even length, the extra iteration swaps the two middle characters back, undoing the earlier swap; for odd lengths the extra iteration swaps the middle character with itself, which is why abc looked correct. Running the loop to n would swap every pair twice and return the original string.
Question 15 · easy
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "loveleetcode";
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
int answer = -1;
for (int i = 0; i < s.length(); i++) {
if (freq.get(s.charAt(i)) == 1) { answer = i; break; }
}
System.out.println(answer);
}
}
The first pass counts every character; the second pass walks the string in its original order and returns the first index whose count is 1. In loveleetcode the letters l and o both appear again later, so the first character seen exactly once is v at index 2. Two linear passes give O(n) time, and the second pass must follow the string, not the map, because the map has no useful order.
Question 16 · easy
This method should count each character, but counts("aba") throws a NullPointerException. Which replacement for the line inside the loop makes it count a as 2 and b as 1?
static Map<Character, Integer> counts(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.get(c) + 1);
}
return map;
}
map.get(c) returns null for a character not yet in the map, and unboxing that null for + 1 throws the exception. merge inserts 1 when the key is absent and otherwise combines the old value with 1, which is exactly a counter; map.getOrDefault(c, 0) + 1 is the other common fix. putIfAbsent never increments, computeIfPresent never inserts, and starting a new key at 0 undercounts every character by one.
Question 17 · hard
Given an unsorted int[] of n values, return the length of the longest run of consecutive integers (for {100, 4, 200, 1, 3, 2} the answer is 4, from 1, 2, 3, 4). The interviewer asks for O(n) expected time. Which approach meets it?
Starting a count only at values with no predecessor means each run is walked exactly once, from its smallest element, so all the upward steps together total at most n and the algorithm is O(n) expected with O(1) HashSet lookups. Counting upward from every value repeats the same run many times and becomes O(n²) on input like 1, 2, ..., n. Sorting and a TreeSet both work but cost O(n log n).
Question 18 · easy
What does this Java 21 program print?
import java.util.*;
public class Main {
static boolean valid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
int k = "([{".indexOf(c);
if (k >= 0) stack.push(")]}".charAt(k));
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(valid("{[()]}") + " " + valid("([)]") + " " + valid("(("));
}
}
For each opening bracket the matching closing bracket is pushed; each closing bracket must equal the top of the stack, which enforces correct nesting, so ([)] fails even though the counts balance. The final isEmpty() check rejects unclosed brackets such as ((. ArrayDeque is the recommended stack in modern Java: the legacy Stack class is synchronized and extends Vector.
Question 19 · medium
Design a stack of ints that supports push, pop, top and getMin, each in O(1) time. Which design works?
The minimum depends on which elements are still on the stack, so it must be remembered per level: the auxiliary stack's top is always the minimum of the elements currently in the main stack, and popping both keeps them in sync. A single min field cannot recover the previous minimum after the minimum is popped. A PriorityQueue makes push O(log n) and removing an arbitrary popped value O(n), and sorting on every push is O(n log n).
Question 20 · medium
An interviewer asks: what is the time complexity of HashMap.get(key) in Java 21?
get hashes the key to a bucket index in O(1) and then compares only the few entries in that bucket, so the average cost is constant when keys spread evenly. If many keys share a bucket, for example because hashCode returns a constant, lookups degrade; since Java 8 a bucket that grows large is converted from a linked list to a balanced tree to limit the damage. A sorted map with guaranteed O(log n) operations is TreeMap, not HashMap.
Question 21 · medium
jobs is an ArrayList with n = 100,000 items, and this method is far slower than expected. What is the cause and the right fix?
static long sumAll(List<Integer> jobs) {
long total = 0;
while (!jobs.isEmpty()) {
total += jobs.remove(0);
}
return total;
}
An ArrayList stores its elements in a contiguous array, so removing index 0 copies all the elements after it, which is O(n) per call and about n²/2 copies in total. ArrayDeque.pollFirst() removes from the front in O(1), and a plain for-each loop over the list does the sum in O(n) without removing anything. isEmpty() and size() are O(1), and an ArrayList does not shrink its array on removal.
Question 22 · hard
You must report whether an int[] of n values contains a duplicate, in O(n log n) time, without allocating any extra collection or array (modifying the input is allowed). Which approach meets both limits?
After sorting, equal values sit next to each other, so a single O(n) scan of neighbours finds a duplicate, and Arrays.sort on a primitive array is O(n log n) and sorts in place. A HashSet gives O(n) expected time but needs O(n) extra memory, which breaks the space limit, and a TreeSet also needs O(n) memory. Nested loops use no extra memory but take O(n²) time; naming this time-versus-space trade-off is the point of the question.
Question 23 · easy
In Spring Boot 3, a handler method returns the string "hello". In a @Controller class the request fails while looking for a view or template named hello; in a @RestController class the client receives hello as the response body. Why the difference?
@RestController is a composed annotation: @Controller with @ResponseBody applied to every handler method. With @ResponseBody, the return value is converted by an HTTP message converter (plain text for a String, JSON for objects via Jackson). In a plain @Controller, a returned String is treated as a logical view name for a template engine.
Question 24 · easy
A client calls GET /users/42/orders?status=PAID, handled by a method mapped with @GetMapping("/users/{id}/orders"). Which parameter list binds 42 and PAID correctly?
@PathVariable binds a {placeholder} segment of the URL path, which identifies the resource, here user 42. @RequestParam binds a query-string parameter after ?, typically a filter, sort or page option. @RequestBody reads the HTTP request body, which a GET request like this does not have. Note that @RequestParam is required by default, so omitting status would give 400 unless you set required = false or a defaultValue.
Question 25 · medium
Several controllers repeat the same try/catch that turns BookNotFoundException into a 404 response. What is the recommended Spring Boot 3 way to handle this?
@RestControllerAdvice (@ControllerAdvice plus @ResponseBody) holds exception handlers that apply to all controllers, so the mapping from an exception to an HTTP status and error body lives in one place. Controllers then just throw, and stay focused on the happy path. Without a handler, an unhandled exception becomes a 500, and returning null from a @RestController gives 200 with an empty body, not 404.
Question 26 · medium
The app sets spring.jpa.open-in-view=false.
@Entity
public class Author {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "author")
private List<Book> books;
// getters
}
@GetMapping("/authors/{id}/book-count")
public int bookCount(@PathVariable Long id) {
Author a = authorRepository.findById(id).orElseThrow();
return a.getBooks().size(); // LazyInitializationException
}
Which change fixes the exception properly?
@OneToMany is lazy by default, so findById returns an author whose books is an uninitialised proxy collection. findById ran in its own short transaction; once it ended the entity was detached, and touching the collection later has no session to load from. Reading it inside a transactional service method, or fetching it up front with join fetch or an @EntityGraph, fixes it; for a count, a countByAuthorId query is even cheaper. Entities are not Spring beans, so @Transactional on one does nothing.
Question 27 · hard
With SQL logging on, this Spring Boot 3 method runs 101 queries for 100 departments.
@Entity
public class Department {
@Id private Long id;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Transactional(readOnly = true)
public int headcount() {
int total = 0;
for (Department d : departmentRepository.findAll()) {
total += d.getEmployees().size();
}
return total;
}
Which change loads the departments with their employees in a single query?
This is the N+1 problem: one query loads the departments, then each lazy getEmployees() fires one more query per department. A join fetch (or @EntityGraph(attributePaths = "employees")) tells JPA to load the collection in the same SQL join. Switching to EAGER does not help here: findAll() runs a JPQL query that does not join the collection, so Hibernate still loads each eager collection with its own select, and now does so on every load of a Department too.
Question 28 · medium
A User entity has a passwordHash field, a lazy @OneToMany list of orders, and each Order has a @ManyToOne back to its User. A junior returns User entities straight from a @RestController. What design should the team adopt?
Exposing entities couples the API to the database schema and leaks fields such as passwordHash. It also makes Jackson walk lazy associations, which causes extra queries or LazyInitializationException, and a bidirectional User/Order pair can recurse endlessly. A DTO decides exactly what the API returns, can change independently of the table, and is filled while the transaction is still open.
Question 29 · medium
A controller calls importAll(rows). When saving an address throws a RuntimeException, that row's customer stays saved in the database. Repositories are injected (omitted).
@Service
public class ImportService {
public void importAll(List<Row> rows) {
for (Row r : rows) {
importOne(r);
}
}
@Transactional
public void importOne(Row r) {
customerRepo.save(r.customer());
addressRepo.save(r.address()); // throws for a bad row
}
}
Why is the customer not rolled back?
@Transactional works through a proxy around the bean: only calls that come in through the proxy are wrapped in a transaction. A call from one method to another on the same object uses this, so the annotation on importOne is ignored, and each repository save runs in its own transaction and commits. Move importOne to a separate bean (or make the outer method transactional) so the call goes through a proxy.
Question 30 · hard
placeOrder is @Transactional. When payment fails it throws a PaymentFailedException (unchecked) and the order is correctly rolled back. A new rule says every payment attempt, including failed ones, must leave a row in payment_attempt. How should this be designed?
REQUIRES_NEW suspends the caller's transaction and runs the method in its own transaction, which commits when that method returns, so the audit row survives when placeOrder later rolls back. It must be called through another bean's proxy: a call to a method on this (and Spring does not proxy private methods) ignores the annotation. Saving inside placeOrder is rolled back with the order, and noRollbackFor would commit the half-placed order too.
Your answers and your score stay in this browser tab. Nothing is sent or saved.