CodeBlanks Logo Icon CodeBlanks

ofNullable

Learn null safety with Optional.ofNullable.

Null-safe wrapping: ofNullable

Optional.ofNullable(value) works even when the value is null: if it is not null it wraps the value, otherwise it returns an empty Optional. This removes the NullPointerException risk.

Example: Optional.ofNullable(maybeNull). If maybeNull is null the result is Optional.empty(); otherwise it is an Optional holding the value. This method is the safe default for data coming from external sources.

Chaining with ofNullable

ofNullable is usually part of a chain. When the value is present you apply map or filter; when it is not the whole chain silently falls through to an empty Optional.

Example: Optional.ofNullable(input).map(String::toUpperCase).orElse("EMPTY"). If input is null the map is skipped and the result is "EMPTY". This pattern collapses nested null checks into a single line, short and readable.

Practice Wrap a possibly null value

Declare a String maybe = null. Build an Optional<String> with Optional.ofNullable(maybe). Print the result of isPresent() with System.out.println.

Starter code

Main.java
import java.util.Optional;

// Wrap a possibly null value
// Use Optional.ofNullable
// Print the isPresent result

Sample solution

Main.java
import java.util.Optional;

public class NullableOptional {
    public static void main(String[] args) {
        String maybe = null;
        Optional<String> opt = Optional.ofNullable(maybe);
        System.out.println(opt.isPresent());
    }
}

Expected output

false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the ofNullable behaviors

Term Meaning
ofNullable(null) Optional.empty()
ofNullable("x") Optional[x]
Optional.of(null) NullPointerException
ofNullable null-safe

2 Which method wraps a null value safely?

  • Optional.of
  • Optional.empty
  • Optional.get
  • Optional.ofNullable Correct answer

Explanation: ofNullable returns an empty Optional for null.

3 Complete the ofNullable call

Question
Optional<String> opt = Optional.____(maybeNull);
Answer
Optional<String> opt = Optional.ofNullable(maybeNull);

Explanation: ofNullable is the null-safe wrapper.

All lessons in Advanced