JvJava

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?

  1. public static void main(String[] args)
  2. public void run()
  3. static int start()
  4. 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?

  1. 3.5
  2. 3
  3. 4
  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);
  1. 2.5
  2. 2
  3. 3
  4. 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?

  1. a == b
  2. a.equals(b)
  3. a.same(b)
  4. 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?

  1. float
  2. double
  3. decimal
  4. 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));
  1. J
  2. a
  3. v
  4. 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);
  1. 12345
  2. 3345
  3. 339
  4. 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);
  1. 6
  2. 10
  3. 15
  4. 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);
  1. null 3
  2. 0 3
  3. 0 2
  4. 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?

  1. const
  2. final
  3. static
  4. readonly
Show answer

Correct: final

final forbids reassignment. (const is reserved, but unused.)

What happens with int[] a = new int[3]; a[3] = 1;?

  1. The array grows automatically
  2. ArrayIndexOutOfBoundsException at runtime
  3. Compiler error
  4. 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?

  1. #
  2. //
  3. --
  4. %%
Show answer

Correct: //

Single-line comments begin with //, multi-line ones go in /* ... */.

What does var x = 5; do?

  1. x is dynamically typed and can later hold text
  2. The compiler infers the type int; x stays statically typed
  3. x becomes a constant
  4. 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?

  1. ArrayList
  2. HashSet
  3. LinkedList
  4. 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);
  1. The list then contains 4 elements
  2. UnsupportedOperationException
  3. Compiler error
  4. 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?

  1. getX()
  2. x()
  3. x
  4. 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));
  1. Punkt@1b6d3586
  2. Punkt(1, 2)
  3. Punkt[x=1, y=2]
  4. {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());
  1. [2, 4]
  2. [4, 16]
  3. [1, 9]
  4. [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));
  1. 0
  2. -1
  3. null
  4. 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?

  1. Serializable
  2. AutoCloseable
  3. Comparable
  4. 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?

  1. NullPointerException
  2. IllegalArgumentException
  3. IOException
  4. 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. 1
  2. F1
  3. 1F
  4. 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);
  1. WD
  2. WE
  3. WEWD
  4. 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?

  1. All spaces are kept
  2. The common indentation of all lines (including the position of the closing """) is removed
  3. Exactly 4 spaces are always removed
  4. 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);
  1. [a, bb, ccc]
  2. [ccc, bb, a]
  3. [a, ccc, bb]
  4. [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?

  1. A class can extend several classes
  2. A class extends at most one class, but can implement many interfaces
  3. A class can implement only one interface
  4. 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. {1=2, 2=2}
  2. {a=1, bb=1, cc=1, d=1}
  3. {2=2, 1=2}
  4. [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);
  1. true
  2. false
  3. Compiler error
  4. 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?

  1. It makes all methods final
  2. It restricts which classes may implement it
  3. It prevents instantiation
  4. 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?

  1. NullPointerException at runtime
  2. Compiler error: the switch is not exhaustive
  3. It simply returns null
  4. 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?

  1. For compute-intensive calculations on all cores
  2. For very many concurrent, blocking I/O tasks
  3. For GPU programming
  4. 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. 1
  2. 2
  3. 0
  4. 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)?

  1. A set with one element
  2. IllegalArgumentException because of a duplicate element
  3. A set with two elements
  4. 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);
  1. 2
  2. 10
  3. 7
  4. 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);
}
  1. 7
  2. 12
  3. 34
  4. 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()));
  1. true true true
  2. false true true
  3. false true false
  4. 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?

  1. Java allows only one thread at a time
  2. ++ is not atomic: read, increment and write can overlap
  3. The garbage collector deletes intermediate values
  4. 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?

  1. It deletes all objects at the end of a method
  2. It frees objects that are no longer reachable by the program
  3. It speeds up the bytecode
  4. 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());
  1. true
  2. false
  3. Compiler error
  4. 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();
  1. p1 p2 p3
  2. p1 p2
  3. p2
  4. 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.