[SOLVED] Why BiPredicate evaluates the two boolean conditions prior to applying the test function – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by MLeiria

Consider this sample code:

public static void main(String[] args){
    SomeObj obj = null;
    if (obj == null || obj.getSomeMethod() == null) {
        System.out.println("Obj is null");
    }

    if (result((x, y) -> x == null || y == null, obj, obj.getSomeMethod())) {
        System.out.println("Obj is null");
    }
}

private static <X, Y> boolean result(final BiPredicate<X, Y> p, final X argX, final Y argY){
    return p.test(argX, argY);
}

In the first If condition I get the message “obj is null” but in the second If condition I get a NullPointerException.
This BiPredicate should’t be a short circuit operator (if the first condition is true don’t bother evaluating the second one)?



Solution

No, you’re passing three arguments to result:

  • The BiPredicate
  • X
  • Y

They get evaluated before calling result, which means the BiPredicate is evaluated and returns a BiPredicate (which is not executed), then X is evaluated, than Y but Y is obj.getSomeMethod() and obj is null, so the NullPointerException is thrown.


This Question was asked in StackOverflow by MLeiria and Answered by Federico klez Culloca It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?