-1

I have seen in many places that the constant value is used first and then the variable for example ("ram").equals(a) and in many places I have seen that the variable is used first and then the constant value with which they want to compare for example a.equals("ram").

what is the difference between a.equals("ram") and ("ram").equals(a) ? which one is better to use and why ?

Saurabh Prakash
  • 2,715
  • 1
  • 11
  • 17
  • `"ram".equals(a)` (not sure why you have parenthesis) is "better" in that it won't throw an NPE is `a` is `null`. – Boris the Spider Feb 18 '17 at 09:18
  • This question has been asked over and over again (for example [here](http://stackoverflow.com/questions/5712100/interview-java-equals)). Please research first. – Seelenvirtuose Feb 18 '17 at 09:19
  • a.equals("ram") can throw a NullPointerException. – Peter Lawrey Feb 18 '17 at 09:22
  • 1
    It’s *very* opinion-based. I happen to have a strong one: If you know `a` may be `null`, use `a != null && a.equals("ram")` to tell the reader that. If you know it cannot, use `a.equals("ram")` to tell the reader that. You are writing code for someone to read it and maintain it. – Ole V.V. Feb 18 '17 at 09:55

2 Answers2

3

The first style is safer in situations when variable a is allowed to be null, because you can skip null checking.

When you write

if (a.equals("ram")) { ... }

you must ensure that a is not null to avoid a null pointer exception. This is not necessary for

if ("ram".equals(a)) { ... }

because equals() method is required to process null arguments without throwing an exception:

For any non-null reference value x, x.equals(null) should return false.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

("ram").equals(a) is better. The code will never break even if a is null. saves us from null pointer exception.

  • 3
    But it will also hide an exception that should be thrown if a is not supposed to be null. – JB Nizet Feb 18 '17 at 09:19
  • 1
    It also reads unnaturally, which impedes maintenance. The premise that it is better to avoid the `null` check is not obviously true, and respondents here have given engineering reasons why it's false. Otherwise the arguments in favor of the backwards idiom are based on emotion, not logic. I won't endorse either form in this comment, only plead that we base our decision on logic. – Lew Bloch Feb 18 '17 at 10:15