Guava - OVERVIEWWhat is Guava? Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. Benefits of Guava
public class GuavaTester {
public static void main(String args[]){ GuavaTester guavaTester = new GuavaTester(); Integer a = null; Integer b = new Integer(10); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Integer a, Integer b){ return a + b; } } Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at GuavaTester.sum(GuavaTester.java:13) at GuavaTester.main(GuavaTester.java:9) Following are the problems with the code.
Let's see the use of Optional, a Guava provided Utility class, to solve the above problems in a standardized way.
import com.google.common.base.Optional;
public class GuavaTester { public static void main(String args[]){ GuavaTester guavaTester = new GuavaTester(); Integer invalidInput = null; Optional<Integer> a = Optional.of(invalidInput); Optional<Integer> b = Optional.of(new Integer(10)); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b){ return a.get() + b.get(); } } Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210) at com.google.common.base.Optional.of(Optional.java:85) at GuavaTester.main(GuavaTester.java:8) Let's understand the important concepts of the above program.
|