Optional 8 java

What is an optional Type in Java 8?

Optional is a Generic class.

Whose purpose is to be a container for a value which may or may not be null.

It was created by java’s Engineers to address the problem of null pointer exception, Which is the most common error in java.

It Is primarily intended for use as a method return type, under specific conditions.

No result is valid vs No result is problem 

Optional tries to solve the problem when no result, or no data is a perfectly valid situation vs no result might really be an error.

You can think of many situations where no data makes sense.

Not everyone has a middle initial in their name, or even a last name for that matter. 

No data for birthdate may or may not be an exception. 

New Inventory may not yet have a sales price. 

Optional is a way of telling you that a value may not be present, therefore you can ignore the value in processing.

Creating an instance of an Optional

Optional is just another generic class, so you declare it like another type, with type arguments.

But you don’t construct an optional.

The downside of optional

Wrapping elements in optional may consume more memory and has the possibility of slowing down execution. 

Wrapping elements in optional adds complexity, and reduces readability of your code.

Optional is not serializable. 

Using optional for fields or method parameter is not recommended

Author: Susheel kumar

Leave a Reply

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