Sobes.tech
Junior — Middle

How do the methods Optional.of() and Optional.ofNullable() differ in usage and behavior?

sobes.tech AI

Answer from AI

The methods Optional.of() and Optional.ofNullable() are used to create Optional objects, but they differ in behavior when passing null:

  • Optional.of(value) — creates an Optional with a non-empty value. If null is passed, it throws a NullPointerException. It is used when you are sure that the value is not null.

  • Optional.ofNullable(value) — creates an Optional that can be empty if null is passed. It does not throw an exception.

Example:

Optional<String> opt1 = Optional.of("Hello"); // OK
Optional<String> opt2 = Optional.of(null); // NullPointerException

Optional<String> opt3 = Optional.ofNullable("Hello"); // OK
Optional<String> opt4 = Optional.ofNullable(null); // Empty Optional

Thus, ofNullable is safer when the value can be null, and of is used when null is not allowed.

How do the methods Optional.of() and… - sobes.tech