← Back to Advanced Java Course | Chapter 3: Functional Programming | Lesson 4 of 6

Java Optional Class

Optional is a box that may or may not hold a value, so you must check before using it. It helps avoid the common crash of using something that is not there.
Syntax
java
Optional<Type> optional = Optional.ofNullable(value);
optional.isPresent();
optional.orElse(defaultValue);
optional.ifPresent(value -> action);

What is Optional?

The Optional class is a container object explicitly designed to represent the presence or absence of a value, rather than using a bare null reference. It helps you handle missing values safely and makes the possibility of 'no value' visible in a method's return type instead of being an implicit, undocumented risk.

Example: What is Optional?

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> name = Optional.of("Meera");
		// Optional wraps a value that may be absent
		Optional<String> empty = Optional.empty();
		// Print a line to the console
		System.out.println(name.isPresent() + " " + empty.isPresent());
	}
}

Checking Presence and Retrieving Values

You can check whether a value is present inside an Optional using isPresent(), and to run some code only when a value actually exists, use the ifPresent() method instead, which avoids an explicit if-check entirely.

Example: Checking Presence and Retrieving Values

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> value = Optional.of("data");
		// Check whether value.isPresent()
		if (value.isPresent()) {
			// Print a line to the console
			System.out.println(value.get());
		}
		value.ifPresent(v -> System.out.println("Present: " + v));
	}
}

Safe Fallback Methods

You can provide a fallback default to use whenever the Optional turns out to be empty, using either orElse(), which always computes the default eagerly, or orElseGet(), which only computes it lazily via a supplier if it's actually needed.

Example: Safe Fallback Methods

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> empty = Optional.empty();
		// Print a line to the console
		System.out.println(empty.orElse("default value"));
		// Print a line to the console
		System.out.println(empty.orElseGet(() -> "computed lazily"));
	}
}

Throwing Exceptions with Optional

If you want a missing value to be treated as an outright error, use the orElseThrow() method to throw a chosen exception instead of silently falling back. This gives you a clean, explicit way to validate that an optional input was actually supplied before continuing.

Example: Throwing Exceptions with Optional

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> value = Optional.of("present");
		// Print a line to the console
		System.out.println(value.orElseThrow(() -> new IllegalStateException("missing value")));
	}
}

Transforming Optionals

You can transform the value inside an Optional using filter() and map(), letting you chain conditions and conversions together in a pipeline that automatically short-circuits to empty if any step fails — very similar in spirit to how a Stream pipeline behaves.

Example: Transforming Optionals

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<Integer> result = Optional.of(10)
			.filter(n -> n > 5)
			.map(n -> n * 2);
		// Print a line to the console
		System.out.println(result.get());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling opt.get() without checking, which throws NoSuchElementException when the Optional is empty; use orElse, ifPresent or isPresent first.
  2. Using Optional.of(value) with a value that might be null, which throws a NullPointerException; use Optional.ofNullable.
  3. Writing orElse(expensiveCall()), which always runs the call even when a value exists; use orElseGet(() -> expensiveCall()) to run it only when needed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.