Both conditional operators && and || are short-circuited as per
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html, which means the second operand
if (true || comparison)
comparison will never be evaluated, since its result is irrelevant (because the first argument is already true).
if(true || (0 > 1))
The first statement is true, and so it is not necessary to evaluate the second.
The or operator is short-circuited when the first operand is true. So,
String foo = null;
if (true || foo.equals("")) {
// ...
}
doesn't throw a NullPointerException
.
As @prajeesh rightly points out in the comments, on way that short-circuiting is used in real code is to prevent a NullPointerException
whenever you are dealing with an API that might return null. So, for instance, if there is a readStringFromConsole
method that returns either the currently available string or null if the user doesn't type anything, we could write
String username = readStringFromConsole();
while (username == null || username.length() == 0) {
// No NullPointerException on the while clause because the length() call
// will only be made if username is not null
System.out.println("Please enter a non-blank name");
username = readStringFromConsole();
}
// Now do something useful with username, which is non-null and of nonzero length
As a side note, an API that returns user input should return the empty string whenever the user doesn't type anything, and shouldn't return null. Returning null is a way of saying "there is nothing available," while returning the empty string is a way of saying "the user didn't type anything" and so is preferred.