sashank
sashank

Reputation: 1541

Will this create NullPointerException , if not why not?

I have this below lines of code

String name = null;
if (something)
    name = 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 ?

Upvotes: 1

Views: 233

Answers (3)

Ramesh PVK
Ramesh PVK

Reputation: 15446

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.

Upvotes: 2

aroth
aroth

Reputation: 54796

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.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881093

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.

Upvotes: 9

Related Questions