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

前端 未结 3 907
北恋
北恋 2020-12-06 16:49

Both conditional operators && and || are short-circuited as per
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html, which means the second operand

相关标签:
3条回答
  • 2020-12-06 17:05
    if (true || comparison)
    

    comparison will never be evaluated, since its result is irrelevant (because the first argument is already true).

    0 讨论(0)
  • 2020-12-06 17:11
    if(true || (0 > 1))
    

    The first statement is true, and so it is not necessary to evaluate the second.

    0 讨论(0)
  • 2020-12-06 17:12

    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.

    0 讨论(0)
提交回复
热议问题