Search code examples
javanulloperator-precedence

Is using the order of evaluation to check for null values bad practice?


If I wish to perform two checks on a string, that it is not null, and that it is not 0 length, I could do this-

if(string != null) {
    if(string.length() > 0) {
        //Do something
    }
}

Or I could do this

if(string != null && string.length() > 0) {
    //Do something
}

As the first check is executed first, the second comparison doesn't happen and a NullPointerException isn't thrown.

Is the second method guaranteed to work in all cases? And if so, would it be considered bad practice to use it?


Solution

  • No, it is perfectly fine and guaranteed to work in all cases.

    Reference from Java specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7