I have this below lines of code
String name = null;
if (something)
name 开发者_Python百科= someString;
if (name != null && name.equals("XYZ"))
doSomethingWith ("hello");
Will the above if condition result in NullPointerException , if "something" is false ? if not why not ?
No, it won't. The &&
operator in Java is a short-circuit one so, if name
is null
, then name.equals()
will not be executed (since false && anything
is still false
).
Same with ||
by the way: if the left hand side evaluates to true
, the right hand side is not checked.
No It wont. The Right Hand Side of && operator gets executed only if the Left Hand Side of && operator is true.
Similarly in case of || operator , if the Left Hand Side is true , the Right Hand Side will not be executed.
No, it won't cause a NullPointerException, because of how the if
statement is written. You have:
if ( name != null && name.equals("XYZ")) {
//do stuff...
}
The conditions in the if
statement are evaluated from left to right. So if name
is null, then the name != null
condition evaluated to false
, and since false && <anything>
evaluates to false
, the name.equals("XYZ")
condition never even gets evaluated.
This behavior is a runtime optimization that avoids executing code that cannot affect the result of the if
statement, and it just so happens to also prevent your example code from ever generating a NullPointerException.
精彩评论