short-circuiting behavior of conditional OR operator(||)

java, operators

Solution

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.

Problem

Both conditional operators && and || are short-circuited as per http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html, which means the second operand does not need to be evaluated at times. Could somebody please provide an example in which the conditional-OR(||) operator would be short-circuited? Short-circuiting behavior is pretty straightforward with the conditional-AND(&&) operator as in: if(false && (1 > 0)) then the second operand:(1 >0) would not need to be evaluated but can't seem to find/think of an example for conditional-OR.

Original source