I found strange behavior in the current version of Java 8. In my opinion, the following code should be good, but the JVM throws a NullPointerException :
Supplier<Object> s = () -> false ? false : false ? false : null; s.get(); // expected: null, actual: NullPointerException
It doesn't matter which lambda expression it is (the same with java.util.function.Function ) or which generic types are used. Instead of false ? : false ? : There may also be more meaningful expressions. The example above is very short. Here is a brighter example:
Function<String, Boolean> f = s -> s.equals("0") ? false : s.equals("1") ? true : null; f.apply("0"); // false f.apply("1"); // true f.apply("2"); // expected: null, actual: NullPointerException
However, these parts of the code work fine:
Supplier<Object> s = () -> null; s.get(); // null
and
Supplier<Object> s = () -> false ? false : null; s.get(); // null
Or with the function:
Function<String, Boolean> f = s -> { if (s.equals("0")) return false; else if (s.equals("1")) return true; else return null; }; f.apply("0"); // false f.apply("1"); // true f.apply("2"); // null
I tested two versions of Java:
~# java -version
openjdk version "1.8.0_66-internal" OpenJDK runtime (build 1.8.0_66-internal-b01) OpenJDK 64-bit server VM (build 25.66-b01, mixed mode)
C:\>java -version
java version "1.8.0_51" Java (TM) SE Runtime Environment (build 1.8.0_51-b16) Java HotSpot (TM) 64-bit server VM (build 25.51-b03, mixed mode)
java ternary-operator lambda jvm
steffen
source share