optional class – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Wed, 17 Jun 2020 09:04:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg optional class – Programmerbay https://programmerbay.com 32 32 What is Optional class in Java 8 https://programmerbay.com/what-is-optional-class-in-java-8/ https://programmerbay.com/what-is-optional-class-in-java-8/#respond Wed, 17 Jun 2020 09:04:47 +0000 https://programmerbay.com/?p=6439 Another feature that Java 8 brought is Optional Class that is capable of representing null or non-null values. It can be defined as  container object which provides a way of handling null check that prevents NullPointerException. It supports  a bunch of utility methods such as isPresent(), filter(), empty(), get() and so on.

Points to remember:

– It is a final class that can handle null pointer exception while working with object.
– It comes under java.util.optional package.

– It is an efficient way of handling null checks that prevents NullPointerException.

– It produces concise code as it also helps us to avoid writing boilerplate codes(Bunch of if and else statements).

Some Important Methods

– isPresent() method identifies whether a value is there or not. It return false if it points to null value

– get() method is used to get values exist in Optional otherwise NoSuchElementException would be thrown

– orElse() : returns value if values are exist otherwise returns other
– empty() : Returns an empty Optional instance
– filter() : uses predicate to filter out undesired values
– map() : uses function to process logic over the given data

Problem:

public class OpationalExample {
    public static void main(String[] args) {
     Integer[] arr = new Integer[1];
        int num = arr[0]/10;
        System.out.println(num);
    }
}

Error:

Exception in thread "main" java.lang.NullPointerException
	at OpationalExample.main(OpationalExample.java:9)

Explanation:

When we try to access an index position which simply doesn’t contain anything and try to perform operation on it, a runtime exception  named NullPointerException is triggered. We can use Optional Class to deal with this problem.

 

Solution:

import java.util.Optional;

public class OpationalExample {
    public static void main(String[] args) {
     Integer[] arr = new Integer[1];
        Optional<Integer > num = Optional.ofNullable(arr[0]);
        if(num.isPresent())
        System.out.println("value :" +(num.get() /10));
        else
            System.out.println("No value exist");
    }
}

Output:

No value exist

]]>
https://programmerbay.com/what-is-optional-class-in-java-8/feed/ 0