The conditions in your if
-statements have to be checked. So, if you have str != null || !str.equals("")
in your if
-statement, then you will check str != null
and then check !str.equals("")
if the first statement is false
. Let's say that the string is null
. The first condition is false
and the second condition tries to check !str.equals("")
. Then you get a NullPointerException, because you can't compare null
to a string.
However, if you use str != null && !str.equals("")
, then str != null
will be checked first and the second statement !str.equals("")
will only be checked if the first one is true
. Meaning, the code will never get to !str.equals("")
if the string is null
. So, you never get the NullPointerException.
You can't use str.equals("")
because null
doesn't have an equals method. By using ==
you check the reference of your string. Everything that is null
has the same reference, so if your string is null
, then it will point to the null
reference, and ==
can be used to check that refernce.