Comparing strings in if :! String.equals (") vs!" ". Equals (string)

Possible duplicate:
The difference between these two conditions?

I'm 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 proposed version over the readability of the original version?

+4
source share
6 answers

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

+7
source
 // Could cause a NullPointerException if billAddress1 is null if(!billAddress1.equals("")) // Will not cause a NullPointerException if billAddress1 is null if (!"".equals(billAddress1)) 
+3
source

!"".equals(billAddress1) will never call NPE , so it allows for a more compact syntax, eliminating billAddress1 == null , which otherwise would be required.

+3
source

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

+2
source

One saves you from NPE, as others have pointed out. But if you are sure that it will not be zero, the best way to check if a string is empty is to use the String.isEmpty() method, which seems to be trying to make the code.

+2
source

The first method may raise a NullPointerException.

+1
source

Source: https://habr.com/ru/post/1447322/


All Articles