1

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?

5
  • 1
    Yes. Why? What happened to you when you tried it out? Commented Sep 15, 2011 at 16:16
  • 1
    why don't you try it out in a junit test? Commented Sep 15, 2011 at 16:16
  • YOu've asked and answered the question already. Commented Sep 15, 2011 at 16:16
  • 1
    I believe you're talking about "Yoda Conditions" Commented Sep 15, 2011 at 16:20
  • still +1 for the question, since the rule "you should start with the constant to avoid nullpointer dereferences" is quite useful. Commented Sep 15, 2011 at 16:22

5 Answers 5

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

His question is the answer. You have to reply in a question format :)
1

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

Comments

1

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.

Comments

1

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.