Your problem is in interpreting the order in which subexpressions are evaluated.
If you have an expression if (a || b)
, it will be evaluated like this:
- If
a
is true, then all expression will be true and b
will not be evaluated.
- If
a
is true, then b
will be evaluated and expression will be true if b
is true or false if b
is false.
Similarly, a if (a && b)
expression will be evaluated like this:
- If
a
is false, then all expression will be false and b
will not be evaluated.
- If
a
is true, then b
will be evaluated and expression will be true if b
is true or false if b
is false.
Note that in the case of
||
, that the first subexpression is true means that the second subexpression will not be evaluated, then any side effects that the second subexpression could produce when evaluated (including a
NullPointerException
) will not happen if first subexpression is true. This also means that doing
if (a || b) {
can give a totally different effect of doing
if (b || a) {
.
In your case, to avoid a NullPointerException
, it makes sense to first check if an object is null
and then try to use it (otherwise it does not make sense). And this is achieved by reversing the order of the subexpressions:
if((!(teste == null)) || !teste.trim().equals("")){
// ...faz algo sem NullPointerException...
}
The reason is that if teste
is null
, then attempting to evaluate teste.trim()
causes NullPointerException
, which is why !(teste == null)
must be before !teste.trim()
. >
However, the code will still not work. There is yet another conceptual error, which can be easily revealed by trying to simplify it. First a !(a == b)
expression is equivalent to a != b
, and therefore (!(teste == null))
is the same as teste != null
. So his expression would look like this:
if (teste != null || !teste.trim().equals("")) {
// ...faz algo sem NullPointerException...
}
Knowing that the second subexpression will only be evaluated when the first subexpression is false, it is questioned: In what circumstance is the first subexpression false? The answer is that this occurs when teste
is null
, so the second subexpression will only be evaluated when teste
is null
. However, if teste
is null
, then you are guaranteed to have NullPointerException
when evaluating the second subexpression!
What you really want is to enter within if
if teste
is not null
E nor is it empty. That is, it was to use &&
instead of ||
:
if (teste != null && !teste.trim().equals("")) {
// ...faz algo sem NullPointerException...
}
Note that this is equivalent to the contour solution you found:
if (sampleString != null) {
if (!sampleString.trim().equals("")) {
// ...faz algo sem NullPointerException...
}
}
What these two if
s do is exactly the same as &&
would do: It will only enter when both expressions are true and the second one will only be evaluated if the first one is true. In fact, one way to simplify if (a) { if (b) { ... }}
is to exactly transform it into if (a && b) { ... }
.