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 · easy
What does this Java 21 program print?
public class Main {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
}
}
String literals with the same text are interned, so a and b point to the same object in the string pool and == is true. new String("java") always creates a new object on the heap, so a == c compares two different references and is false. equals compares the characters, which is why you should always compare String content with equals.
Question 2 · easy
What does this Java 21 program print?
public class Main {
public static void main(String[] args) {
String s = "Hi";
s.concat(" there");
StringBuilder sb = new StringBuilder("Hi");
sb.append(" there");
System.out.println(s + " | " + sb);
}
}
Strings are immutable: concat returns a new String and leaves s unchanged, and here the returned value is thrown away. StringBuilder is mutable, so append changes the builder itself. To keep the result with a String you must reassign it, as in s = s.concat(" there").
Question 3 · 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 4 · 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 5 · easy
What does the equals and hashCode contract in Java require?
Equal objects must have equal hash codes, because hash-based collections use the hash code to find where a key is stored. The reverse is not required: two unequal objects may share a hash code (a collision), and the collection then tells them apart with equals. A hash code only has to be consistent with equals, not unique.
Question 6 · easy
What does this Java 21 program print?
public class Main {
static class Parent {
Parent() { System.out.print("Parent "); }
}
static class Child extends Parent {
Child() { System.out.println("Child"); }
}
public static void main(String[] args) {
new Child();
}
}
Every constructor starts by calling a superclass constructor; when you do not write super(...), the compiler inserts a call to the no-argument super(). So the Parent constructor finishes before the body of Child runs. Objects are always built from the top of the hierarchy down.
Question 7 · 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 8 · hard
What does this Java 21 program print?
public class Main {
static class A {
String name = "A";
String get() { return name; }
}
static class B extends A {
String name = "B";
String get() { return name; }
}
public static void main(String[] args) {
A x = new B();
System.out.println(x.name + " " + x.get());
}
}
Fields are not polymorphic: x.name is resolved at compile time from the declared type A, so it reads the field declared in A. Methods are overridden, so x.get() runs B.get(), which reads the name field declared in B. The B field only hides the A field; it does not replace it.
Question 9 · 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 10 · medium
This Java 21 code throws ConcurrentModificationException. Which fix is correct?
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer n : nums) {
if (n % 2 == 0) {
nums.remove(n);
}
}
System.out.println(nums);
The enhanced for loop uses an iterator, and ArrayList iterators are fail-fast: changing the list directly while iterating makes the next call to next() throw. Removing through the iterator itself, or with removeIf, keeps the list and the iterator in step. The problem has nothing to do with threads, and LinkedList iterators are fail-fast too.
Question 11 · medium
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(10, 20, 30));
list.remove(1);
list.remove(Integer.valueOf(10));
System.out.println(list);
}
}
A list of Integer has two remove methods: remove(int index) and remove(Object o). The int literal 1 matches remove(int) exactly, so the element at index 1 (20) goes; Integer.valueOf(10) is an object, so remove(Object) deletes the value 10. Box the argument explicitly when you mean to remove by value.
Question 12 · medium
You add employee records to a map keyed by employee ID in no particular order, and a report must list them in ascending ID order. Which map is the best choice?
TreeMap is a red-black tree that keeps its keys sorted, so iterating it gives ascending IDs with no extra sorting step. HashMap and Hashtable make no promise about iteration order, and any order you happen to see can change as the map grows. LinkedHashMap keeps insertion order, not sorted order.
Question 13 · easy
What does this Java 21 program print?
import java.util.Arrays;
public class Main {
static void reverse(int[] a, int lo, int hi) {
while (lo < hi) {
int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
lo++; hi--;
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
reverse(a, 1, 4);
System.out.println(Arrays.toString(a));
}
}
The two-pointer reversal swaps a[lo] and a[hi] and moves both pointers inward until they meet, so only the range from index 1 to index 4 (both inclusive) is reversed: 2, 3, 4, 5 becomes 5, 4, 3, 2. It runs in O(n) time with O(1) extra space, which is why interviewers expect it instead of copying into a new array. The same helper, called three times, also rotates an array in place.
Question 14 · easy
What does this Java 21 program print?
public class Main {
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++; j--;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("racecar") + " " + isPalindrome("Madam")
+ " " + isPalindrome("abba"));
}
}
The check compares characters from both ends moving inward and stops when the pointers meet, which works for odd and even lengths alike, so abba is a palindrome. charAt comparison is case-sensitive: 'M' and 'm' are different characters, so Madam fails. If the interviewer wants case to be ignored, compare Character.toLowerCase of both characters.
Question 15 · 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 16 · 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 17 · easy
A candidate builds a comma-separated string of n numbers with result += nums[i] + ","; inside a loop. What should they say about this when the interviewer asks about performance?
Strings in Java are immutable, so every concatenation allocates a new String and copies the characters of the old one, and the copies grow with each iteration, giving quadratic total work. The compiler optimises concatenation within a single expression, not across loop iterations. A StringBuilder keeps one growable buffer, so each append is amortized O(1) and the loop is linear.
Question 18 · medium
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] nums = {3, 2, 4};
int target = 6;
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) { System.out.println(j + " " + i); return; }
seen.put(nums[i], i);
}
System.out.println("none");
}
}
One-pass two-sum looks up the complement target - nums[i] before inserting the current value, so an element is never paired with itself: at index 0 the map is empty, so 3 is not matched with itself to make 6. At index 2 the complement 2 is found at index 1, and the earlier index is printed first. This gives O(n) time with an O(n) HashMap, instead of the O(n²) nested-loop solution.
Question 19 · medium
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> groups = new HashMap<>();
for (String w : words) {
char[] c = w.toCharArray();
Arrays.sort(c);
groups.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
}
System.out.println(groups.size() + " " + groups.get("aet"));
}
}
Sorting the letters of each word gives a canonical key, so all anagrams share one key: aet for eat, tea and ate, ant for tan and nat, and abt for bat, which makes 3 groups. computeIfAbsent creates the list the first time a key is seen and the words are appended in input order. The key must be a String built from the sorted array; using the char[] itself as a key would fail because arrays use identity equality.
Question 20 · 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 21 · medium
A queue is built from two stacks (ArrayDeques used with push and pop). offer(x) pushes onto in. poll() pops from out, and only when out is empty does it first pop every element of in and push it onto out. What is the time complexity of poll()?
Every element is pushed onto in once, moved to out once and popped from out once, so n operations do O(n) total work, which is amortized O(1) per operation. A single poll() that finds out empty can still cost O(n) for the transfer. Moving elements back after each poll would destroy this guarantee and make the queue O(n) per operation.
Question 22 · hard
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] a = {2, 7, 3, 5, 4, 6, 8};
int[] next = new int[a.length];
Arrays.fill(next, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
while (!stack.isEmpty() && a[stack.peek()] < a[i]) next[stack.pop()] = a[i];
stack.push(i);
}
System.out.println(Arrays.toString(next));
}
}
The stack holds indices of elements still waiting for a greater value to their right, in decreasing order of value. When a[i] is larger than the value at the top, it is the next greater element for that index, so the index is popped and answered; indices never answered keep -1. Each index is pushed and popped at most once, so this monotonic-stack solution is O(n) instead of the O(n²) scan to the right for every element.
Question 23 · medium
This BFS should list each node once in breadth-first order. On the graph with edges 0 -> 1, 0 -> 2, 1 -> 3 and 2 -> 3 it returns [0, 1, 2, 3, 3]. Which fix is right?
static List<Integer> bfs(List<List<Integer>> adj, int start) {
List<Integer> order = new ArrayList<>();
Deque<Integer> queue = new ArrayDeque<>();
boolean[] visited = new boolean[adj.size()];
queue.offer(start);
while (!queue.isEmpty()) {
int u = queue.poll();
visited[u] = true;
order.add(u);
for (int v : adj.get(u)) if (!visited[v]) queue.offer(v);
}
return order;
}
A node must be marked visited when it is added to the queue, not when it is removed; otherwise two neighbours can both enqueue the same node before it is ever polled, which is how 3 gets in twice. Checking order has the same flaw, since 3 is still waiting in the queue when node 2 is processed, and it adds an O(n) scan per edge. Switching to a stack or push changes the order to depth-first without fixing the duplicates.
Question 24 · easy
An interviewer asks why most Spring Boot 3 teams prefer constructor injection over @Autowired on fields. Which answer is the strongest?
With constructor injection every required dependency is a constructor argument, so the fields can be final and the object is never created without them. Tests need no Spring context or reflection: new OrderService(fakeRepo) is enough. Field injection still works in Spring Boot 3, but it hides dependencies and leaves them null outside the container; constructor injection actually makes circular dependencies fail fast instead of allowing them.
Question 25 · easy
In Spring Boot 3, a @Service class keeps a counter in an instance field:
@Service
public class VisitService {
private int visits;
public int recordVisit() {
return ++visits;
}
}
Two controllers inject VisitService and many users call it at the same time. What is true?
The default bean scope is singleton: the container creates one instance and injects that same object everywhere. Every request thread therefore shares the visits field, and ++visits is a read-modify-write that can lose updates under concurrency. Keep singleton beans stateless, or use something like AtomicInteger or a database when shared state is really needed.
Question 26 · medium
Spring Boot 3 fails at startup with NoUniqueBeanDefinitionException: expected single matching bean but found 2: cardGateway,upiGateway.
public interface PaymentGateway { void charge(long paise); }
@Component
public class UpiGateway implements PaymentGateway { /* ... */ }
@Component
public class CardGateway implements PaymentGateway { /* ... */ }
@Service
public class CheckoutService {
private final PaymentGateway gateway;
public CheckoutService(PaymentGateway gateway) { this.gateway = gateway; }
}
Checkout should use UPI. Which change fixes it?
Injection is by type, and two beans implement PaymentGateway, so Spring cannot pick one. @Qualifier("upiGateway") names the bean to inject (the default bean name is the class name with a lower-case first letter). Marking UpiGateway with @Primary would also work when it should be the default everywhere; @Autowired or @Lazy do not remove the ambiguity.
Question 27 · medium
@Service, @Repository and @Controller are all specialisations of @Component. What does @Repository add beyond being picked up by component scanning?
All stereotype annotations register the class as a bean, and they also document the layer the class belongs to. @Repository additionally marks the class for persistence exception translation, so a caller sees a consistent DataAccessException (for example DataIntegrityViolationException) instead of a vendor- or JPA-specific exception. It does not start transactions or change the scope; beans stay singletons unless told otherwise.
Question 28 · hard
A singleton ExportService needs a freshCsvWriter for every export, because CsvWriter keeps per-export state. CsvWriter is a @Component with @Scope("prototype") and has its own injected dependencies. How should ExportService get a new instance on each call?
A prototype bean injected into a singleton is created once, when the singleton is built, and then reused for the singleton's whole life. Asking the container each time, by calling getObject() on an injected ObjectProvider of CsvWriter (or through a @Lookup method), returns a new, fully injected instance per call. Making ExportService prototype only moves the problem to whoever injects it, and new bypasses the container, so CsvWriter's own dependencies would be null.
Question 29 · medium
spring-boot-starter-validation is on the classpath of this Spring Boot 3 app.
public record SignupRequest(@NotBlank String name, @Email String email) {}
@PostMapping("/signup")
public ResponseEntity<Void> signup(@RequestBody SignupRequest req) {
userService.register(req);
return ResponseEntity.ok().build();
}
A request with "name": "" and "email": "abc" is accepted and saved. Which change makes Spring reject it with 400 Bad Request?
Constraint annotations on a class only describe the rules; Spring MVC runs Bean Validation on a @RequestBody argument only when the parameter is marked @Valid (or @Validated). With it, a violation throws MethodArgumentNotValidException, which Spring turns into a 400 response by default and which a @RestControllerAdvice can map to a clearer error body. @NotNull would still accept an empty string, and a request DTO is not a bean.
Question 30 · medium
POST /api/books creates a book and the new book gets id 17. Following REST conventions, what should the Spring Boot 3 controller return?
201 Created is the status for a request that created a new resource, and the Location header tells the client the URL of that resource; returning the created representation in the body saves a follow-up GET. 200 works but hides the fact that something was created, and 204 sends nothing back, not even the new id. 202 Accepted means the work was queued and has not finished yet, which is not the case here.
Your answers and your score stay in this browser tab. Nothing is sent or saved.