The line in question is return pFile.exists() ? true : null;. As it does not raise any compilation error, what is the explanation for this. It ended up raising NPE.
import java.io.File;
public class Main {
public static void main(String... args) {
boolean accept = accept(new File(""));
System.out.println("accept = " + accept);
}
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
return pFile.exists() ? true : null; //this line should throw compilation error
}
}
pFile is not null; a File is instantiated as you can see. But obviously the file is not there. The question is not about pFile. I am interested in how the operator is dealing with null.
You code is equivalent to:
On other words, the type of the conditional operator is
Booleanin this case, and then the value is being unboxed to return aboolean. Whennullis unboxed, you get an exception.From section 15.25 of the Java Language Specification:
I believe that’s the case that’s applicable here, although I’ll grant it’s not as clear as it might be.