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. Ifnullis passed, it throws aNullPointerException. It is used when you are sure that the value is notnull. -
Optional.ofNullable(value)— creates an Optional that can be empty ifnullis 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.