Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using Optional type in Java

Today I am going to show you what it is Optional type in Java and how to use it correctly. Java 8 provides us with a new Optional class, which allows for better protection against null pointer exceptions.

Optional type - variations and usage

Empty Optional object


public static Optional empty() {
@SuppressWarnings("unchecked")
Optional t = (Optional) EMPTY;
return t;
}

Way to use:

@Test
public void createsEmptyOptional()
Optional empty = Optional.empty();
assertThat(empty.isPresent(), is(false));
}

So we created empty optional object and in next step we use isPresent() to check if insde optional object is any value.

Optional of some object


public static Optional of(T value) {
return new Optional(value);
}

Way to use:


@Test
public void createsOptionalUsingOf() {
String toTest = "to test";
Optional empty = Optional.of(toTest);
assertThat(empty.isPresent(), is(true));
}

So we created non empty optional object and in next step we use isPresent() to check if insde optional object is any value present.

Null Pointer Exception with optional type

But what happens when we pass null to the Optional object?


@Test (expected = NullPointerException.class)
public void createsOptionalUsingOf() {
String toTest = null;
Optional empty = Optional.of(toTest);
assertThat(empty.isPresent(), is(false));
}

We should expect null pointer exception.

Optional ofNullable to the rescue


public static Optional ofNullable(T value) {
return value == null ? empty() : of(value);
}

Way to use


@Test
public void createsOptionalUsingOfNullable() {
String toTest = null;
Optional empty = Optional.ofNullable(toTest);
assertThat(empty.isPresent(), is(false));
}

So when we use ofNullable to create optional object we do not get null pointer exception when we pass null parameter. Insted we get an empty optional object.

From Java 11 we can use both isEmpty() and isPresent() methods to check if optional object is empty.

Optional type summary

We need to remember not to over-use Optional type and not to over-engineer. For example it makes perfect sense to use it as a return type, especially in the methods that finds something.

We should avoid using it as a class members or as arguments to methods or constructors. Sometimes there are exceptions when we can justify such usage.

That's it as a short introduction to it.


This post first appeared on IT Code Hub - Java, Mobile Apps, Linux And More, please read the originial post: here

Share the post

Using Optional type in Java

×

Subscribe to It Code Hub - Java, Mobile Apps, Linux And More

Get updates delivered right to your inbox!

Thank you for your subscription

×