I'm trying to get into the functional aspect of Java 8 and am having trouble getting the Optional class components working.
In the following code I intentionally call a component outside of the bounds of an array to see if I can use Optional to avoid getting an exception.
public class Driver {
public static void main(String[] args)
{
BiFunction<Integer, Integer, String> add = (a, b) ->
{
Integer operation = a + b;
return "The answer is " + operation.toString();
};
System.out.println(add.apply(5,4));
Integer[] numArray = {1,2,3,4};
Optional<Integer> number = Optional.ofNullable(numArray[8]);
number.ifPresent(num ->
{
num = number.get();
System.out.println(num);
});
Integer hi = numArray[1];
System.out.println(hi);
}
When I run this code trying to get numArray[8], called with Option.ofNullable, and using ifPresent, I still get the exception below.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
My understanding is that the number.get call shouldn't happen if numArray[8] is null. Am I missing something?