0

In part of the code for check empty string the programmer use equals() like this:

if ("".equals(name)) {
    // some logic
}

Why is it executed from a string value directly? What is the difference from this;

if (name.equals("")) {
    // some logic
}

Both of them have the same result, but what is the idea behind doing the first one?

buræquete
  • 14,226
  • 4
  • 44
  • 89
test testt
  • 23
  • 1

1 Answers1

4

The idea behind using;

"".equals(name)

is that "" can never be null, whereas name can be. equals() accepts null as a parameter, but trying to execute a method from a null variable will result in a NullPointerException.

So this is a shorthand way to evade such possible exceptions. Same goes for any such constant object.

e.g.

final Integer CONSTANT_RATE = 123456;
....

if (CONSTANT_RATE.equals(someVariable)) { .. }

rather than doing;

if (someVariable != null && someVariable.equals(CONSTANT_RATE)) { .. }
buræquete
  • 14,226
  • 4
  • 44
  • 89