Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Projects

Java Projects

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Reference

Java Reference Java Keywords Java String Methods Java StringBuilder Methods Java Math Methods Java Output Methods Java Arrays Methods Java ArrayList Methods Java LinkedList Methods Java HashMap Methods Java Scanner Methods Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A


Java Optional


Share

Java Optional

In the HashMap chapter, you used get() to find a value by its key. But what if the key does not exist? Then get() returns null, which means "no value".

If you forget to check for null and use the value anyway, the program crashes:

Example

HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Norway", "Oslo");

String city = capitalCities.get("Spain");
System.out.println(city.toUpperCase());  // Error

"Spain" is not in the map, so city is null. Calling toUpperCase() on null stops the program with a NullPointerException.

An Optional solves this. It is like a box that either holds a value or is empty. Before you can use the value, you have to open the box, so you always decide what should happen when it is empty.


Create an Optional

Import java.util.Optional, and create an Optional with one of these methods:

  • Optional.of(value) creates a box with a value
  • Optional.empty() creates an empty box
  • Optional.ofNullable(value) creates a box with the value, or an empty box if the value is null

The type inside <> tells Java what the box can hold, just like with ArrayList<String>. Use isPresent() to check if the box has a value:

Example

import java.util.Optional;

public class Main {
  public static void main(String[] args) {
    Optional<String> name = Optional.of("Liam");
    Optional<String> noName = Optional.empty();

    System.out.println(name.isPresent());    // true
    System.out.println(noName.isPresent());  // false
  }
}

Try it Yourself »



Get the Value with orElse()

The orElse() method returns the value if there is one. If the box is empty, it returns the default value that you give it:

Example

Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();

System.out.println(name.orElse("Guest"));    // Liam
System.out.println(noName.orElse("Guest"));  // Guest

Try it Yourself »

Note: An Optional also has a get() method, but it gives an error if the box is empty. Use orElse(), or check with isPresent() first.


Run Code If There Is a Value

The ifPresent() method runs code only when the box has a value. You give it the code as a lambda expression:

Example

Optional<String> name = Optional.of("Liam");
name.ifPresent(n -> System.out.println("Hello " + n));  // Hello Liam

Try it Yourself »

If name was empty, nothing would be printed.


Real-Life Example

Optional is most useful as the return value of a method that might not find anything. Here is the capital cities example from the start of this page, now with Optional:

Example

import java.util.HashMap;
import java.util.Optional;

public class Main {
  static Optional<String> findCapital(String country) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "London");
    capitalCities.put("Norway", "Oslo");
    return Optional.ofNullable(capitalCities.get(country));
  }

  public static void main(String[] args) {
    System.out.println(findCapital("Norway").orElse("Not found"));  // Oslo
    System.out.println(findCapital("Spain").orElse("Not found"));   // Not found
  }
}

Try it Yourself »

The method returns an Optional<String> instead of a String. This shows everyone who uses the method that the result can be missing, and orElse() handles that case without a crash.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.