Complementing the answers already given, but giving names to the steers, ||
and &&
are what is called short-circuit evaluation. This means that if the first part of the expression being evaluated (ie, the one on the left) is true for the expression tested, the second part of the nor is checked.
String nome = "Luis";
int idade = 10;
if(nome == null && idade == 10) {
//não entra aqui
}
For the code of a if
block to be executed, the evaluated expression must be true ( true
). When using the &&
operator, this means that both sides must be true
so that the expression is true
. In the example, when evaluating the first part of the expression, nome == null
, it is false, so the compiler already knows that the expression as a whole is no longer true (both sides must be true
, remember? ), so he does not even evaluate the right side of the expression. This is why it's called a short circuit, the compiler does not even go to the end of the evaluation, it leaves before.
if(nome == null || idade == 10) {
//o código aqui dentro é executado
}
An evaluation with ||
, in turn, requires that only one side of the expression be true
so that the expression as a whole is also true
. Thus, nome == null
is false, but since there is still another side to be evaluated that can be true
, the compiler also evaluates it. As idade == 10
is true, the expression as a whole returns true
and the code inside if
is executed.
If the first side is already true
face, the compiler does not even have to evaluate the other side, since, as said, with ||
, only one side is true
so that the expression as a whole is also true
. It would again be a short circuit.