Signup/Sign In

Difference Between orElse and orElseGet methods of Optional class in Java 8

Posted in Programming   LAST UPDATED: OCTOBER 12, 2021

    In Java 8 a lot of new APIs were included in Java to help developers cater to the bigger algorithmic problems rather than wasting time on smaller details. In this direction, a new class named Optional is introduced in Java 8 to have a better way of handling objects which may have null value during some program's execution. We covered the Optional class in our last article No more NullPointerExceptions.

    The Optional class provides with two different methods to assign a default value to any variable/object if it is assigned a null value when the Optional class object is being created.

    We can use orElse() like this,

    String mayBeNull = null;
    Optional<String> opt = Optional.ofNullable(mayBeNull).orElse('Studytonight');

    Similarly, we can use orElseGet() method, but instead of providing a default value, it takes a funtional interface as argument, and whatever that function returns becomes the default value.

    Let's see an example,

    String mayBeNull = null;
    // setting default value using lambda function inside orElseGet
    Optional<String> opt = Optional.ofNullable(mayBeNull).orElseGet(()->"Sudytonight");

    See, they are more or less similar. But are they exactly similar?


    Difference Between orElse and orElseGet

    It's time to unveil the difference, let's take an example, where we will take a string variable, we will assign it a null value and then encapsulate it inside an Optional class object and will try to assign a default value to it.

    Let's create a function which we will provide an argument to both these methods,

    public String setDefault() {
        System.out.println("Setting default value...");
        return "Default";
    }

    Now the main code,

    String testStr;
    String orElseGetStr = Optional.ofNullable(testStr).orElseGet(this::setDefault);
    System.out.println("Default String for orElseGet is: " + orElseGetStr);
    String orElseStr = Optional.ofNullable(testStr).orElse(setDefault());
    System.out.println("Default String for orElse is: " + orElseStr);

    And the output for this will be,

    Setting default value...

    Default String for orElseGet is: Default

    Setting default value...

    Default String for orElse is: Default

    Just as expected. Let's try once again with a non null value,

    String testStr = "Studytonight";
    String orElseGetStr = Optional.ofNullable(testStr).orElseGet(this::setDefault);
    System.out.println("Default String for orElseGet is: " + orElseGetStr);
    String orElseStr = Optional.ofNullable(testStr).orElse(setDefault());
    System.out.println("Default String for orElse is: " + orElseStr);

    And the output for this will be,

    Default String for orElseGet is: Studytonight

    Setting default value...

    Default String for orElse is: Default

    What? In case of orElse() method, still the function is called and a default object is being created, which will never be used as the value is present for the variable wrapped in the Optional object. But orElseGet() works just fine, and the functional interface is never even invoked.

    Now, we should not worry about an orphan default object getting created in the case above, because JVM knows very well how to collect garbage. But what if the function call is some web service call or some database call, we wouldn't want to do that.

    And this is the difference between orElse and the orElseGet API provided by the Optional class introduced in Java 8.

    NEVER HESITATE: If you have any doubt, share with us by commenting down below.

    You may also like:

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:JavaOptionalJava8
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS