4

Possible Duplicate:
Difference between these two conditions?

I am doing some code cleanup and NetBeans made a suggestion to change

if(!billAddress1.equals("")) to if (!"".equals(billAddress1)).

What is the difference between the two, and the advantages of using the suggested version over the readability of the original version?

Community
  • 1
  • 1
Robert H
  • 11,520
  • 18
  • 68
  • 110

6 Answers6

8

billAddress1.equals("") will cause a NullPointerException if billAddress1 is null, "".equals(billAddress1) wont.

jlordo
  • 37,490
  • 6
  • 58
  • 83
3
// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))

// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
3

!"".equals(billAddress1) will never cause an NPE, so it allows a more compact syntax by allowing to get rid of the billAddress1 == null that would otherwise be required.

Samuel Rossille
  • 18,940
  • 18
  • 62
  • 90
2

The latter will not cause a Null pointer exception if the value is null.

DaBaer
  • 204
  • 1
  • 7
2

One saves you from NPE as others have pointed out. But if you are sure it's not going to be null then the better way to check if a string is empty is to use the String.isEmpty() method, that's what the code seems to be trying to do.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1

The first one has a potential to cause NullPointerException.

droidchef
  • 2,237
  • 1
  • 18
  • 34