-1

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?

  • 2
    This isn't a `NullPointerException`, it's an `ArrayIndexOutOfBoundsException`. – Andy Turner Feb 25 '18 at 22:37
  • "intentionally call a component outside of the bounds of an array"... Optional can't prevent any errors done by that action. Array indexing doesn't return an optional value – OneCricketeer Feb 25 '18 at 22:40
  • Aside: `num = number.get();` isn't necessary. You've already got the number from `number` in the `num` variable. – Andy Turner Feb 25 '18 at 22:44

1 Answers1

2

numArray[8] is not null. It doesn't exist. Evaluating this expression is precisely what throws the ArrayIndexOutOfBoundsException, since, as its name implies, you're trying to access an index that is out of bounds.

Optional is completely irrelevant here.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255