HJW
HJW

Reputation: 23443

"Null variable checking" in String

Generally, is there a difference between

if("x".equalsIgnoreCase(myStrVar))

and

if(myStrVar.equalsIgnoreCase("x"))

in that the first will not cause a null pointer exception, but the second one will if in both scenarios myStrVar is null?

Upvotes: 1

Views: 399

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1500065

Yes, that's correct. However, that doesn't mean you should always use the former ("safe") version.

If you are absolutely confident that myStrVal is non-null - meaning that for it to be null would indicate a bug - I would probably use the second form.

  • I find it more readable (in the same way that I would write if (x == 0) rather than if (0 == x)
  • If the value is null, it's probably better to go bang as early as possible, rather than continuing while in an unexpected state

So:

  • If you want to have special handling for myStrVal being null, then perform a check for that first
  • If you want to treat myStrVal being null in the same way as any other non-"x" value, use the first form
  • If you want to treat myStrVal being null as a bug, use the second form

Upvotes: 7

DaveFar
DaveFar

Reputation: 7447

Exactly, because the implementation is

public boolean equalsIgnoreCase(String anotherString) {
    return (this == anotherString) ? true :
           (anotherString != null) && (anotherString.count == count) &&
           regionMatches(true, 0, anotherString, 0, count);
}

This is a nice instance of the (Yoda Conditions-)rule: "you should start with the constant to avoid nullpointer dereferences".

Upvotes: 1

Sahil Muthoo
Sahil Muthoo

Reputation: 12519

Obviously a NullPointerException will be raised in the second scenario if myStrVar == null. You can't call equalsIgnoreCase(String str) on null but you can pass in null as an argument.

Upvotes: 1

NPE
NPE

Reputation: 500247

Your statement that the second version would cause a NullPointerException, whereas the first one wouldn't, is correct.

Upvotes: 1

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

If I got your question right, the answer is "yes". :)

Upvotes: 1

Related Questions