Repaso
EspaƱol
Java CoreIntermediateJV-20

What is the recommended way to use Optional<T>?

Options

  1. Call optional.get() directly each time you need a value
  2. Return type for 'maybe absent', with orElse or map (Correct option)
  3. Use it for each field and each method parameter, always
  4. Use it as a way to make a class thread-safe in Java

Answer

Use it as a return type for "might be absent", and use orElse, orElseThrow, map instead of get() without checking

Why

Optional<T> is a box that may or may not contain a value. It makes "this can be missing" visible in the method signature, instead of returning null and hoping callers remember to check.

Good use: repo.findById(id).map(User::getName).orElse("unknown") or .orElseThrow().

Bad use: calling .get() without checking (it throws if empty), or using Optional for fields and parameters.

Remember

Optional is for return values; avoid bare get().

Key terms

Practice this question in Repaso