It is sometimes useful not to specify a value for a variable.If a class variable is unassigned then it has null value.In such scenario we can use Optional class in Java 8 for optional values.
Optional is a useful class if we want to specifying whether a variable will have some assigned value or not.We define such a variable as Optional type.
The difference between a normal variable and an optional variable is we don’t need to assign a null value to specify absence of value.If specify
absent value using the empty method of the Optional type.For example we can specify an empty value for an optional variable as:
Optional<Integer> optVar=Optional.empty();
Similarly we can specify a value for an optional variable as:
Integer sampleValue=1; Optional<Integer> optVar=Optional.of(sampleValue);
Following is the complete example:
import java.util.Optional;
public class SampleClass {
public static void main(String args[]){
SampleClass obj = new SampleClass();
if(obj.Check())
System.out.println("value is present");
else
System.out.println("value not present for optional type");
}
Integer a=1;
Optional<Integer> opt=Optional.of(a);
public boolean Check()
{
System.out.println("going to check value");
if(opt.isPresent()) {
return true;
}
else
{
return false;
}
}
}
Leave a Reply