Complementing the answers already given, but naming the oxen, ||
and &&
are what is known as short-circuit evaluation. This means that if the first part of the expression being evaluated (i.e., the one on the left) is true for the expression tested, the second part of the expression is not even checked.
String nome = "Luis";
int idade = 10;
if(nome == null && idade == 10) {
//não entra aqui
}
So that the code of a block if
is executed, the expression evaluated must be true (true
). When using the operator &&
, that means both sides should be true
for the expression to be true
. In the example, when evaluating the first part of the expression, nome == null
, it is false, so the compiler already knows that there is no longer how the expression as a whole be true (both sides must be true
, Remember? ), so he doesn’t even evaluate the right side of the expression. That’s why it’s called short-circuiting, the compiler doesn’t even go to the end of the evaluation, it comes out before.
if(nome == null || idade == 10) {
//o código aqui dentro é executado
}
A review with ||
, in turn, requires that only one side of the expression be true
so that expression as a whole may also be true
. Thus, nome == null
is false, but as there is still another side to be evaluated and that can be true
, compiler evaluates it as well. How idade == 10
is true, the expression as a whole returns true
and the code within the if
is executed.
In case the first side was already true
at first, the compiler would not even need to evaluate the other side, since, as said, with ||
just one side being true
so that expression as a whole may also be true
. It would be a short-circuit again.