Java 8 - Part2 Optional Class
Java 8 - Part2 Optional Class
Java introduced a new class Optional in jdk8. It is a public final class and
used to deal with NullPointerException in Java application. You must import
java.util package to use this class. It provides methods which are used to
check the presence of value for particular variable.
/*ispresent()
* isempty()
* ifpresent()
* orElse()
* orElseget()
* get()
* orElseThrow()
*/
public static <T> Optional<T> of(T It returns an Optional with the specified present
value) non-null value.
public boolean equals(Object obj) Indicates whether some other object is "equal
to" this Optional or not. The other object is
considered equal if:
o It is also an Optional and;
o Both instances have no value present or;
o the present values are "equal to" each
other via equals().
public int hashCode() It returns the hash code value of the present
value, if any, or returns 0 (zero) if no value is
present.
Sample Program:
import java.util.Optional;
public class OptionalMethods {
static void print() {
System.out.println("welcomes you");
}
static String Name() {
return "i am orelseget() method call";
}
public static void main(String[] args) {
/*ispresent()
* isempty()
* ifpresent()
* orElse()
* get()
* orElseget()
* orElseThrow()
*/
Optional<String> obj=Optional.of("a");
System.out.println("ispresent o/p "+obj.isPresent());//true
String s="ranjima";
Optional<String> obj1=Optional.ofNullable(s);
System.out.println(obj1.isPresent());
System.out.println("isempty result "+obj1.isEmpty());
//ifpresent()
obj1.ifPresent(str->System.out.println(str.length()));
obj1.ifPresent(str->OptionalMethods.print());
//orElse()
String place=null;//string
Optional<String> ref=Optional.ofNullable(place);//string value will be replaced
System.out.println(ref.orElse("tamilnadu"));
//get();
System.out.println(obj);//Optional[a]
System.out.println(obj.get());//a
//orElseget()
String name=null;
Optional<String> st=Optional.ofNullable(name);
System.out.println(st.orElseGet(()->OptionalMethods.Name()));
Optional op=Optional.ofNullable(null);
System.out.println(op);
//Optional.empty
//orelsethrow
try {
st.orElseThrow(()->new Exception("please check the value is present"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Optional val=Optional.of("ranjini");
System.out.println(val);
System.out.println(val.get());
}
}