Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings in an if: !string.equals("") vs !"".equals(string) [duplicate]

Tags:

java

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?

like image 642
Robert H Avatar asked Nov 30 '22 22:11

Robert H


2 Answers

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

like image 84
jlordo Avatar answered Dec 11 '22 01:12

jlordo


// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))

// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
like image 21
Juan Mendes Avatar answered Dec 11 '22 00:12

Juan Mendes