Java quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
Which method is the entry point of a classic Java program?
- public static void main(String[] args)
- public void run()
- static int start()
- public static void init()
Show answer
Correct: public static void main(String[] args)
The JVM starts a program with public static void main(String[] args).
What does 7 / 2 give with two int values?
- 3.5
- 3
- 4
- 2
Show answer
Correct: 3
With two int operands, / is an integer division that truncates the fractional part: 3.
What does this code print?
int x = 10;
x /= 4;
System.out.println(x);- 2.5
- 2
- 3
- 4
Show answer
Correct: 2
x /= 4 is x = x / 4 with integer division: 10 / 4 = 2.
How do you correctly compare two strings by content?
- a == b
- a.equals(b)
- a.same(b)
- a === b
Show answer
Correct: a.equals(b)
For objects, == only compares the reference. Content is compared with equals.
What type does the literal 3.14 have?
- float
- double
- decimal
- real
Show answer
Correct: double
Decimal-number literals are double by default. For float you need the suffix f (3.14f).
What does this code print?
String s = "Java";
System.out.println(s.charAt(1));- J
- a
- v
- 1
Show answer
Correct: a
Indexes start at 0: charAt(0) is J, charAt(1) is a.
What does this code print?
System.out.println(1 + 2 + "3" + 4 + 5);- 12345
- 3345
- 339
- 15
Show answer
Correct: 3345
From the left: 1 + 2 = 3 (number), then "3" makes "33", after that 4 and 5 are appended as text: 3345.
What is the output?
int summe = 0;
for (int i = 1; i <= 4; i++) {
summe += i;
}
System.out.println(summe);- 6
- 10
- 15
- 4
Show answer
Correct: 10
1 + 2 + 3 + 4 = 10 (the loop runs up to and including 4).
What does this code print?
int[] a = new int[3];
System.out.println(a[0] + " " + a.length);- null 3
- 0 3
- 0 2
- Error
Show answer
Correct: 0 3
int arrays are pre-filled with 0. length is the number of elements (3), not a method call.
Which keyword turns a variable into a constant?
- const
- final
- static
- readonly
Show answer
Correct: final
final forbids reassignment. (const is reserved, but unused.)
What happens with int[] a = new int[3]; a[3] = 1;?
- The array grows automatically
- ArrayIndexOutOfBoundsException at runtime
- Compiler error
- The value is ignored
Show answer
Correct: ArrayIndexOutOfBoundsException at runtime
Valid indexes are 0 to 2. Accessing index 3 throws an ArrayIndexOutOfBoundsException at runtime.
How does a single-line comment begin in Java?
- #
- //
- --
- %%
Show answer
Correct: //
Single-line comments begin with //, multi-line ones go in /* ... */.
What does var x = 5; do?
- x is dynamically typed and can later hold text
- The compiler infers the type
int; x stays statically typed - x becomes a constant
- It is a syntax error
Show answer
Correct: The compiler infers the type int; x stays statically typed
var is only type inference: the type (here int) is fixed at compile time and cannot change.
Which collection stores each value at most once?
- ArrayList
- HashSet
- LinkedList
- ArrayDeque
Show answer
Correct: HashSet
A Set contains no duplicates; HashSet is the most common implementation.
Intermediate (13 questions)
What happens with this code?
List<Integer> l = List.of(1, 2, 3);
l.add(4);- The list then contains 4 elements
- UnsupportedOperationException
- Compiler error
- ArrayIndexOutOfBoundsException
Show answer
Correct: UnsupportedOperationException
List.of creates an immutable list; modifications throw an UnsupportedOperationException at runtime.
What is the automatically generated accessor method for the field x of a record called?
- getX()
- x()
- x
- get("x")
Show answer
Correct: x()
Records generate accessor methods with the field name itself: punkt.x().
What does this code print?
record Punkt(int x, int y) {}
System.out.println(new Punkt(1, 2));- Punkt@1b6d3586
- Punkt(1, 2)
- Punkt[x=1, y=2]
- {x=1, y=2}
Show answer
Correct: Punkt[x=1, y=2]
Records generate a useful toString() method in the format Name[field=value, ...].
What does this code print?
System.out.println(
List.of(1, 2, 3, 4).stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.toList());- [2, 4]
- [4, 16]
- [1, 9]
- [4, 8]
Show answer
Correct: [4, 16]
filter keeps 2 and 4, map squares them: [4, 16].
What does this code print?
Optional<String> o = Optional.empty();
System.out.println(o.map(String::length).orElse(-1));- 0
- -1
- null
- NoSuchElementException
Show answer
Correct: -1
An empty Optional stays empty with map, and orElse(-1) then returns the fallback value -1.
What must an object implement in a try-with-resources header?
- Serializable
- AutoCloseable
- Comparable
- Runnable
Show answer
Correct: AutoCloseable
AutoCloseable (or Closeable) defines close(), which is called automatically at the end of the block.
Which of these exceptions is a checked exception?
- NullPointerException
- IllegalArgumentException
- IOException
- ArithmeticException
Show answer
Correct: IOException
IOException inherits from Exception, not from RuntimeException – the compiler requires catch or throws.
What does this code print?
static int f() {
try {
return 1;
} finally {
System.out.print("F");
}
}
System.out.println(f());- 1
- F1
- 1F
- F
Show answer
Correct: F1
finally runs before the method is left: first F is printed, then println outputs the return value 1 – F1.
What does this code print?
int tag = 6;
String s = switch (tag) {
case 6, 7 -> "WE";
default -> "WD";
};
System.out.println(s);- WD
- WE
- WEWD
- Compiler error
Show answer
Correct: WE
The case 6 matches, and the switch expression returns WE. There is no fall-through.
How are the leading spaces determined in a text block?
- All spaces are kept
- The common indentation of all lines (including the position of the closing """) is removed
- Exactly 4 spaces are always removed
- Text blocks must not be indented
Show answer
Correct: The common indentation of all lines (including the position of the closing """) is removed
Java removes the smallest common indentation; the closing """ counts too, which lets you control the indentation.
What does this code print?
var l = new ArrayList<>(List.of("ccc", "a", "bb"));
l.sort(Comparator.comparing(String::length));
System.out.println(l);- [a, bb, ccc]
- [ccc, bb, a]
- [a, ccc, bb]
- [bb, a, ccc]
Show answer
Correct: [a, bb, ccc]
Sorting is ascending by length: 1, 2, 3 gives [a, bb, ccc].
What holds for inheritance and interfaces in Java?
- A class can extend several classes
- A class extends at most one class, but can implement many interfaces
- A class can implement only one interface
- Interfaces cannot be inherited
Show answer
Correct: A class extends at most one class, but can implement many interfaces
Java allows only single inheritance for classes, but any number of interfaces.
What does this code print?
var m = Stream.of("a", "bb", "cc", "d")
.collect(Collectors.groupingBy(String::length, Collectors.counting()));
System.out.println(m);- {1=2, 2=2}
- {a=1, bb=1, cc=1, d=1}
- {2=2, 1=2}
- [2, 2]
Show answer
Correct: {1=2, 2=2}
Grouping is by length. There are two strings of length 1 and two of length 2. The HashMap prints small Integer keys in ascending order: {1=2, 2=2}.
Advanced (13 questions)
What does this code print?
Integer c = 1000, d = 1000;
System.out.println(c == d);- true
- false
- Compiler error
- Depends on the operating system
Show answer
Correct: false
Only values from -128 to 127 come from the Integer cache. With 1000 two objects are created, and == compares references: false.
What does the keyword sealed do on an interface?
- It makes all methods final
- It restricts which classes may implement it
- It prevents instantiation
- It makes the interface thread-safe
Show answer
Correct: It restricts which classes may implement it
A sealed type lists the permitted subtypes (permits); this way the compiler knows all cases for exhaustive switch expressions.
What happens if a switch expression over a sealed interface does not cover a subtype and has no default?
- NullPointerException at runtime
- Compiler error: the switch is not exhaustive
- It simply returns null
- It is silently ignored
Show answer
Correct: Compiler error: the switch is not exhaustive
Switch expressions must be exhaustive. For sealed types the compiler checks this and reports missing cases.
What are virtual threads (Java 21) mainly intended for?
- For compute-intensive calculations on all cores
- For very many concurrent, blocking I/O tasks
- For GPU programming
- For running without a JVM
Show answer
Correct: For very many concurrent, blocking I/O tasks
Virtual threads are cheap: when one waits for I/O, the carrier thread becomes free. For pure CPU load they bring nothing.
What does this code print?
record R(int a) {}
Set<R> s = new HashSet<>();
s.add(new R(1));
s.add(new R(1));
System.out.println(s.size());- 1
- 2
- 0
- Compiler error
Show answer
Correct: 1
Records generate equals and hashCode based on the fields. Both R(1) are equal, so the set contains only one element.
What happens with Set.of(1, 1)?
- A set with one element
- IllegalArgumentException because of a duplicate element
- A set with two elements
- Compiler error
Show answer
Correct: IllegalArgumentException because of a duplicate element
Set.of rejects duplicates and throws an IllegalArgumentException. The constructor new HashSet<>(...), by contrast, silently removes duplicates.
What does this code print?
int r = CompletableFuture.supplyAsync(() -> 2)
.thenApply(x -> x * 5)
.join();
System.out.println(r);- 2
- 10
- 7
- A CompletableFuture object
Show answer
Correct: 10
thenApply transforms the result 2 into 10, join waits and returns it.
What does this code print?
record P(int x, int y) {}
Object o = new P(3, 4);
if (o instanceof P(int a, int b)) {
System.out.println(a * b);
}- 7
- 12
- 34
- Nothing is printed
Show answer
Correct: 12
The record pattern destructures P into a = 3 and b = 4; 3 * 4 = 12.
What does this code print?
String a = "hi";
String b = new String("hi");
System.out.println((a == b) + " " + a.equals(b) + " " + (a == b.intern()));- true true true
- false true true
- false true false
- false false true
Show answer
Correct: false true true
new String creates a new object (a == b is false), equals compares content (true), intern() returns the object from the string pool, i.e. the same one as the literal a (true).
Why does zaehler++ from two threads (100000 times each) not always give 200000?
- Java allows only one thread at a time
++is not atomic: read, increment and write can overlap- The garbage collector deletes intermediate values
- int is too small for such large numbers
Show answer
Correct: ++ is not atomic: read, increment and write can overlap
Without synchronization, updates get lost (race condition). Use AtomicInteger, synchronized or locks.
What does the garbage collector do?
- It deletes all objects at the end of a method
- It frees objects that are no longer reachable by the program
- It speeds up the bytecode
- It closes files automatically
Show answer
Correct: It frees objects that are no longer reachable by the program
The GC detects unreachable objects on the heap and cleans them up. You still have to close resources such as files yourself (try-with-resources).
What does this code print?
System.out.println(new ArrayList<String>().getClass()
== new ArrayList<Integer>().getClass());- true
- false
- Compiler error
- ClassCastException
Show answer
Correct: true
Because of type erasure the type parameters no longer exist at runtime: both objects have the class ArrayList.
What does this code print?
Stream.of(1, 2, 3)
.peek(x -> System.out.print("p" + x + " "))
.filter(x -> x > 1)
.findFirst();- p1 p2 p3
- p1 p2
- p2
- Nothing, because no final result is used
Show answer
Correct: p1 p2
Streams are lazy: element 1 is filtered out (but peek ran), element 2 passes the filter, findFirst stops – p3 is never processed.