Sobes.tech
Junior — Middle

What are the consequences of returning null from an Optional object and then calling the get method?

sobes.tech AI

Answer from AI

If you return null from Optional (for example, Optional.of(null)), it will lead to a NullPointerException when creating the Optional, since of does not allow null.

If the Optional is empty (Optional.empty()) and then you call the get() method, a NoSuchElementException will be thrown because there is no value.

Therefore:

  • Never pass null to Optional.of().
  • Before calling get(), check for the presence of a value using isPresent() or use methods that handle the absence of a value (orElse, orElseGet).

Example:

Optional<String> opt = Optional.ofNullable(null); // creates an empty Optional
opt.get(); // will throw NoSuchElementException
What are the consequences of returning null from an… - sobes.tech