> For the complete documentation index, see [llms.txt](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/lambda/optional-in-functional-programming.md).

# Optional in Functional Programming

**Introduction to Optional Class:**

The `Optional` class in Java is a container object that may or may not contain a non-null value. It is a part of Java's functional programming features introduced to avoid `NullPointerException` by explicitly representing the absence of a value.

**Using Optional in Lambda Expressions:**

Using `Optional` in lambda expressions can make your code more expressive and safer by eliminating null checks.

**Example of Using Optional in Lambda Expressions:**

```java
import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        String name = "Alice";
        Optional<String> nameOptional = Optional.ofNullable(name);

        // Using Optional in lambda expression
        nameOptional.ifPresent(n -> System.out.println("Hello, " + n)); // Output: Hello, Alice
    }
}
```

In this example, `Optional.ofNullable(name)` creates an `Optional` instance from a nullable value. The `ifPresent` method takes a lambda expression and executes it only if the optional contains a non-null value.

**Avoiding Null Checks with Optional:**

`Optional` helps avoid explicit null checks by providing methods for handling both present and absent values.

**Example of Avoiding Null Checks with Optional:**

```java
import java.util.Optional;

public class NullCheckExample {
    public static void main(String[] args) {
        String name = null;
        Optional<String> nameOptional = Optional.ofNullable(name);

        // Avoiding null checks using Optional
        String result = nameOptional.orElse("Unknown"); // Default value if name is null
        System.out.println("Name: " + result); // Output: Name: Unknown
    }
}
```

In this example, `nameOptional.orElse("Unknown")` provides a default value ("Unknown") if the `Optional` is empty, eliminating the need for explicit null checks.

Using `Optional` in functional programming promotes more concise and safer code by making the absence of a value explicit. It encourages developers to handle both present and absent values explicitly, leading to more predictable and readable code.
