0

I know they both give same results.

String str="";
System.out.println("".equals(str));
System.out.println(str.equals(""));

Which one is efficient?

  • 4
    The difference is that if `str` is null, then `"".equals(str)` will return `false`, but `str.equals("")` will throw a `NullPointerException`. – khelwood Jun 26 '18 at 09:09
  • There is no difference in term of efficiency. If ever there was one, it would be so insignificant that you don't have to bother about that. – vincrichaud Jun 26 '18 at 09:09
  • The whole point of having string literals before the equals methods are to avoid the NullPointerException. – Sunder R Jun 26 '18 at 09:11
  • This is a precautionary Approach. Called Yoda Condition where `A Yoda condition places the constant portion of the expression on the left side of the conditional statement.` here you can avoid NullPointerException. – Sagar Kharab Jun 26 '18 at 09:14
  • 2
    Neither. Use str.isEmpty(). If you want to accept the case when str is null without an error, use str != null && str.isEmpty() – kumesana Jun 26 '18 at 09:16

2 Answers2

1

The first one is called yoda condition and avoid null pointer exception

the second one work fine if str is defined, but you need to handle null condition

Both do the exact same thing, and both are understandable by everyone.

However some programmers consider yoda as bad practice, as it decrease readability. I would also add that sometimes, you want to catch null values, so yoda notation is useless.

Kepotx
  • 1,095
  • 12
  • 26
  • 2
    I'd actually wager that while it is funny to listen to Yoda talking, and you can indeed understand what Master Jedi says while he is talking by making the extra effort, it is annoying to do so when trying to be professional and achieving things. – kumesana Jun 26 '18 at 09:15
  • @kumesana I though criticize yoda condition will make my answer kind off opinion-based, so I stay neutral, but I edit it, hope it's better now – Kepotx Jun 26 '18 at 09:25
  • Okay. I think your answer was fine from the beginning, as it's not possible to talk of every issues in the world at once. Was just adding to it for those who may be interested to know more. But as you wish. – kumesana Jun 26 '18 at 09:27
  • The best implementations that avoid yoda condition, and increase readability is `str != null && str.equals("")` or `str != null && str.isEmpty()` – vincrichaud Jun 26 '18 at 10:56
1

In case of empty string that you have passed, there is no difference, both return true.

But writing: "".equals(str);

is considered as safer than:

str. equals(""); - the second one throws a NullPointerException if str is null, when the first one in that case simply returns false amd you don't need to deal with checking if str is null.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21