Optional get Method

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

In this tutorial, we will demonstrate how to get a value from the Optional class object using the get() method.

Get Value from Optional Object in Java - get() Method

The get() method returns a value if it is present in this Optional otherwise throws NoSuchElementException.

In the below example, the get() method returns a value because the value is present in the Optional class object:

package com.java.lambda.optional;

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String value = stringOptional.get();
        System.out.println(value);
    }
}
Output:
ramesh@gmail.com

In the below example, the get() method throws the NoSuchElementException because the value is not present in the Optional class object:

package com.java.lambda.optional;

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String value = stringOptional.get();
        System.out.println(value);
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:143)
	at com.java.lambda.optional.OptionalDemo.main(OptionalDemo.java:10)

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare