Pick an option and check it. The explanation shows after each answer. Take as long as you like; nothing is timed and nothing is sent.
20 questions
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 · 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 9 · 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 10 · 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 11 · 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 12 · 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 13 · 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 14 · 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 15 · 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 16 · 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 17 · 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 18 · 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 19 · 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 20 · 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.
Your answers stay in this browser tab. Nothing is sent or saved.