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

Java Optional Class

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;
public class Main {
	public static void main(String[] args) {
		Optional<String> name = Optional.of("Meera");
		Optional<String> empty = Optional.empty();
		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;
public class Main {
	public static void main(String[] args) {
		Optional<String> value = Optional.of("data");
		if (value.isPresent()) {
			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;
public class Main {
	public static void main(String[] args) {
		Optional<String> empty = Optional.empty();
		System.out.println(empty.orElse("default value"));
		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;
public class Main {
	public static void main(String[] args) {
		Optional<String> value = Optional.of("present");
		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;
public class Main {
	public static void main(String[] args) {
		Optional<Integer> result = Optional.of(10)
			.filter(n -> n > 5)
			.map(n -> n * 2);
		System.out.println(result.get());
	}
}
🔒

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.