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,097
  • 18
  • 67
  • 107

6 Answers6

8

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

jlordo
  • 36,534
  • 6
  • 55
  • 79
3
// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))

// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
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
  • 17,907
  • 18
  • 59
  • 87
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
  • 49,592
  • 20
  • 90
  • 140
1

The first one has a potential to cause NullPointerException.

droidchef
  • 2,066
  • 1
  • 15
  • 32