
Guava - OPTIONAL CLASSOptional is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values. Class Declaration Following is the declaration for com.google.common.base.Optional<T> class:
@GwtCompatible(serializable=true)
public abstract class Optional<T> extends Object implements Serializable Class Methods
This class inherits methods from the following class:
Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java
import com.google.common.base.Optional;
public class GuavaTester { public static void main(String args[]){ GuavaTester guavaTester = new GuavaTester(); Integer value1 = null; Integer value2 = new Integer(10); //Optional.fromNullable - allows passed parameter to be null. Optional<Integer> a = Optional.fromNullable(value1); //Optional.of - throws NullPointerException if passed parameter is null Optional<Integer> b = Optional.of(value2); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b){ //Optional.isPresent - checks the value is present or not System.out.println("First parameter is present: " + a.isPresent()); System.out.println("Second parameter is present: " + b.isPresent()); //Optional.or - returns the value if present otherwise returns //the default value passed. Integer value1 = a.or(new Integer(0)); //Optional.get - gets the value, value should be present Integer value2 = b.get(); return value1 + value2; } } Verify the Result Compile the class using javac compiler as follows:
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
First parameter is present: false
Second parameter is present: true 10 |