Skills101
← All practice quizzes

Quiz: Java Optional

5 questions · new set on every retakeNo time limitPass: 60%+10 XP on first pass

Use Optional to make "there may be no result" visible in your method signatures. Creating Optionals, orElse vs orElseGet, orElseThrow, map, flatMap and filter chains, and where Optional should not be used.

Log in to take the quiz

Free account · see your score, answers and explanations, earn XP

  1. Question 1

    What does this print?

    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            Optional<String> o = Optional.ofNullable(null);
            System.out.println(o.map(String::length).orElse(-1));
        }
    }
    
  2. Question 2

    What happens with Optional.of(null)?

  3. Question 3

    What is the difference between orElse(x()) and orElseGet(() -> x())?

  4. Question 4

    What does this print?

    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            Optional<Integer> m = Optional.of(35);
            System.out.println(m.filter(x -> x >= 40).map(x -> "pass").orElse("fail"));
        }
    }
    
  5. Question 5

    When should you use flatMap instead of map on an Optional?

🎯 Today’s placement challenge — 10 questions, no login. Can you score 10/10?Take today’s challenge →