# 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://muhammad-tri-wibowo.gitbook.io/java-tutorials/lambda/optional-in-functional-programming.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
