🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Java Optional: all 10 questions

Quiz: Java Optional · Question 7 of 10

What does this print? (code)

What does this print?

import java.util.*;
public class Main {
    static int calls = 0;
    static String fallback() { calls++; return "x"; }
    public static void main(String[] args) {
        Optional<String> o = Optional.of("a");
        o.orElse(fallback());
        o.orElseGet(Main::fallback);
        System.out.println(calls);
    }
}
  1. A.0
  2. B.1
  3. C.2
  4. D.Compile error
Answer & explanation

Correct answer: 1

orElse(fallback()) runs fallback even though a value is present; orElseGet does not.

Can you get the rest right without peeking?

Take the timed Quiz: Java Optional quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →