1.

Optional Class in Java 8

Answer»

Optional is a container object which might not contain a non-null value. If a value is AVAILABLE, isPresent() will RETURN true and get() will return the value. Supplementary methods that rely on the availability of a contained value are provided, like orElse() methods (return a default value if value not present) and ifPresent()(execute a block of code if the value is present).

Syntax for optional class

public final class Optional<T> extends Object

Optional class is a value based class. Operations pertaining to identity including reference equality (==), identity hash code, or synchronization on objects of the class may have unprecedented outcomes and should be avoided.

Let us see an example where the isPresent() method of the optional class is used:

import JAVA.util.Optional;    public class Example {       public static void main(String[] ARGS)    {        String s1 = new String("Hello");        String s2 = null;        Optional<String> obj1 = Optional.ofNullable(s1);        Optional<String> obj2 = Optional.ofNullable(s2);        if (obj1.isPresent())    // checks if String object is present        {           System.out.println(s1.toUpperCase());           }        else        System.out.println("s1 is a Null string");        if(obj2.isPresent())   // checks if String object is present        {             System.out.println(s1.toUpperCase());        }        else        System.out.println("s2 is a Null string");    } }

The OUTPUT is as follows:

$javac Example.java $java Example HELLO s2 is a Null string


Discussion

No Comment Found