🎙 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 1 of 10

What does this print? (code)

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));
    }
}
  1. A.0
  2. B.-1
  3. C.null
  4. D.NullPointerException
Answer & explanation

Correct answer: -1

ofNullable(null) is empty, map does nothing on an empty Optional, and orElse gives -1.

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 →