Java Optional Class | Java 8

ByDasun De Silva

Nov 3, 2021

The null pointer exception is one of the most classic of all errors. Normally developers use try catch blocks to handle this. But with Java 8 , we can use optional classes.

With optional class we can store objects and can check object is available or not. Java Optional class is introducded under java.util package.

String vehicle = "Benz CLA200";
String vehicle2 = "Benz AMG";

/**With Optional.of we can store vehicle String insider opt optional. But to use Optional.of the object should not be null. 
However if you feel is the variable can be null for any reasons then you can use Optional.ofNullable method. 
**/
Optional<String> optionalVehicle = Optional.of(vehicle);
Optional<String> optionalVehicle = Optional.ofNullable (vehicle2 );

Now you know you can assign any object to optional variable and now we can check how it is going to handle null pointers. Check below example. You can use ifPresent method to check an object is null or not.

String vehicle = "Benz CLA200";
Optional<String> optionalVehicle = Optional.ofNullable (vehicle2 );
optionalVehicle.ifPresent(vehicle -> startVehicle(vehicle) );

In addtionally we can default value is the vehicle string is null. And you can even trigger exceptions as well. Check below example.

//How to set default value 
String vehicle = "Benz CLA200";
String defaultVechile = "Toyota Camry";
Optional<String> optionalVehicle = Optional.ofNullable (vehicle2 ).orElse(defaultVechile);

//How to trigger exception if the object is null
String vehicle = "Benz CLA200";
Optional<String> optionalVehicle = Optional.ofNullable (vehicle2 ).orElseThrow(IllegalArgumentException::new);

I hope now you have good understanding on Optional classes and usage in Java. Subscribe pickocode youtube channel further technical stuff.

Leave a Reply