3

Optional Class in java 8

 2 years ago
source link: https://blog.knoldus.com/optional-class-in-java-8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Optional Class in java 8

Reading Time: 2 minutes

In this blog, we will understand what is the optional class and do we really need it?

When you start writing the code in any project and one thing you always care that is the

Null pointer exception and we apply many checks to prevent this error and try that error

Never come in our code. that’s why we want something so that we can avoid this.

What is optional class?

Optional class provides another way to handle situations when value may or may not be present. Till now you would be using null to indicate that no value is present but it may lead to problems related to null references.
A container object which may or may not contain a non-null value. If a value is present,
isPresent() will return true and get() will return the value.

// java code without optional class

public class Demo {

     public static void main(String arr[]) {

        Integer[] array = new Integer[5];
        int value = array[2] + 10;
        System.out.println(value);
     }
}

Output :

Exception in thread "main" java.lang.NullPointerException
at Demo.main(Test.java:8)

To avoid this type of error and abnormal behaviour we use this beautiful feature that is an Optional class

so if we use these features our program can execute without crashing.

// java code without optional class
import java.util.Optional;

public class Demo {

    public static void main(String arr[]) {

        Integer[] array = new Integer[5];
        Optional<Integer> checkNull =
                Optional.ofNullable(array[2]);
        if (checkNull.isPresent()) {
            int value = array[2] + 10;
            System.out.print(value);
        } else
            System.out.println("value is null");
    }
}

Output :

value is null

General structure of Optional class :

public final class Optional <T> extends Object
Here T is the type of the value stored in the Optional instance.
Note: that Optional instance may contain value or it may be empty, but if it contains value then it is of type T.

Method Summary

Method Descriptionempty()Returns an empty Optional instanceequals(Object obj)Indicates whether some other object is “equal to” this Optional.get()If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.isPresent()Return true if there is a value present, otherwise false.of(T value)Returns an Optional with the specified present non-null valueofNullable(T value)Returns an Optional describing the specified value, if non-null, otherwise returns an empty OptionalorElse(T other)Return the value if present, otherwise return other.orElseThrow(Supplier exceptionSupplier)Return the contained value, if present, otherwise throw an exception to be created by the provided suppliertoString()Returns a non-empty string representation of this Optional suitable for debugginghashCode()Returns the hash code value of the present value, if any, or 0 (zero) if no value is present.

Conclusion :

  • When we use the optional class than in our code no chance to create a NullPointerException.
  • Optional class gives the way to avoid the NullPointerException. so basically before optional class very hard to avoid it without using too many null checks.
  • With the Optional class we develop the clean and neat APIs and Optional.empty() method is useful to create an empty Optional object.
  • Optional.isPresent() returns true when the object is not null and not empty otherwise it gives the return a false value.
  • There is another method present in the Optional class, which only executes if the given Optional object is non-empty, the method is ifPresent().
  • Optional class orElseGet() return the value if the Object is not null and not empty and if the the Object is empty then return the default value which we pass in the argument.

References :

For more information on Optional Class, Click here.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK