Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javamedium

What is `Optional` used for, and what is a common misuse?

Tags
#optional#null-safety#api
Back to categoryPractice quiz

Answer

`Optional` represents a value that may be present or absent and forces the caller to handle the empty case. A common misuse is using it as a field in entities/DTOs everywhere; it’s mainly intended for return values, not for serialization or persistence fields.

Optional<User> user = repo.findById(id);
String name = user.map(User::getName).orElse("unknown");

Advanced answer

Deep dive

Expanding on the short answer — what usually matters in practice:

  • Context (tags): optional, null-safety, api
  • JVM: memory (heap/stack), GC, and what drives latency.
  • Contracts: equals/hashCode/toString, mutability and consequences.
  • Performance: boxing, allocations, collections, inlining.
  • Explain the "why", not just the "what" (intuition + consequences).
  • Trade-offs: what you gain/lose (time, memory, complexity, risk).
  • Edge cases: empty inputs, large inputs, invalid inputs, concurrency.

Examples

Here’s an additional example (building on the short answer):

Optional<User> user = repo.findById(id);
String name = user.map(User::getName).orElse("unknown");

Common pitfalls

  • Too generic: no concrete trade-offs or examples.
  • Mixing average-case and worst-case (e.g., complexity).
  • Ignoring constraints: memory, concurrency, network/disk costs.

Interview follow-ups

  • When would you choose an alternative and why?
  • What production issues show up and how do you diagnose them?

Related questions

Testing
What is contract testing and when is it useful?
#contract-testing#api#microservices
Security
How do you protect a public API from abuse?
#rate-limiting#abuse#api
TypeScript
How do optional properties work in TypeScript?
#optional
  • How would you test edge cases?
  • #types
    Next.js
    Route Handlers in the App Router: how do you define them and what are they used for?
    #nextjs#route-handlers#api
    Kotlin
    `lateinit` vs nullable property: when would you choose `lateinit`?
    #kotlin#lateinit#null-safety
    Microservices
    BFF (Backend for Frontend): what is it and when does it help?
    #microservices#bff#api