What is Optional.get() in Java?

Introduction

I will discuss here what is Optional.get() in Java. Optional is a class and get() is a method in this class. Java 8 was a huge improvement to the platform and one of the new features was added Optional.get().

So using this feature you are telling that a value may or may not be available or present in the variable used by Optional.

So if value is not present then it will throw NullPointerException.

To avoid such NullPointerException you can check whether value is present or not using isPresent() method.

Example

Let’s consider below code snippets:

Optional<String> name = Optional.of("Soumitra");
if (name.isPresent()) {
	System.out.println(name.get());
} else {
	System.out.println("value not present");
}

So when you run, you will get output: Soumitra.

Now change the above code snippets as follows:

name = Optional.empty();
if (name.isPresent()) {
	System.out.println(name.get());
} else {
	System.out.println("value not present");
}

Your output should be as value not present.

But when you change the value as empty as shown below and try to get value then you will get exception:

name = Optional.empty();
System.out.println(name.get());

You will get exception as java.util.NoSuchElementException: No value present.

You can also use Optional.orElse() method to provide other than default value.

You can find an example on Optional.get() in the tutorial link Spring REST Optional Path variable.

Leave a Reply

Your email address will not be published. Required fields are marked *