Doubt about logical operators && e || in Java

Asked

Viewed 12,886 times

5

I have the following code in my app:

if (aquaName != null && !aquaName.getText().toString().isEmpty()){
    values.put(NAME_COLUMN, aquaName.getText().toString().trim());
} else {
    Toast.makeText(this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
    return;
}

Why if I use || in place of && I don’t reach the condition else?

I’ve read here on the stack about | & || && but I can’t understand.

6 answers

7


The use of the operator && or the operator || will depend on your condition. The operator && will be used when all conditions must be NECESSARILY true, example:

if(a && b && c && d){
    //Se todas forem verdade
}else{
   //Se qualquer delas foram mentira
}

See the letters a, b, c and d as conditions, so if they are all true you will enter the if, If at least one of them isn’t real, you’ll be in else.

For the operator ||, called OU, will allow you to enter the if if at least one condition is true, that is, if a, b, c or d is true will enter the if, if all were false, will enter the else,example:

if(a || b || c || d){
    //Se algumas (ao menos uma) for verdade
}else{
   //Se todas forem mentira (falsa)
}

For your example:

if (aquaName != null && !aquaName.getText().toString().isEmpty()){
    values.put(NAME_COLUMN, aquaName.getText().toString().trim());
} else {
    Toast.makeText(this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
    return;
}

will only enter the else if aquaName is void and (&&) if it is empty.

4

Because || (or) if any of the conditions return true he executes the if.

Example:

aquaName = "" // (vazio)
aquaName != null // verdadeiro
!aquaName.getText().toString().isEmpty() // falso

Running your if, already using && only if all the conditions are true does he perform his if, if he does not fall in LSE.

1

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.

1

Split:

  • aquaName != null will be true if aquaName is not null, i.e., has any value ("test", "", ", etc.")
  • !aquaName.getText().toString().isEmpty() will be true if it is empty (on behalf of !).

Using the ||, would enter the if if one of the conditions were true. Considering what you have, if your first condition is true, the second condition is false, and vice versa.


For operators, use a (| &) or two (|| &&) "just" forces the execution of what comes next; using as example your condition,

if (aquaName != null && !aquaName.getText().toString().isEmpty())

In that case, if aquaName is different from null, he already enters the if. Using only one operator,

if (aquaName != null & !aquaName.getText().toString().isEmpty())

even though aquaName be equal to null, he will do the validation !aquaName.getText().toString().isEmpty().

I suggest you give a read in that article, will help you understand well when using this type of comparator.

1

|| is equivalent to "or" and && is equivalent to "and"

in its condition the first has to be different from null And the second different from empty.

then the two conditions have to be true, if it were used || only one would already stand as true.

1

https://en.wikipedia.org/wiki/De_Morgan's_laws

If you observe, the block else harbors a message saying that Name cannot be empty.

Soon, the block if should harbor a case that

  • be the negation of the case else
  • the block else must execute whether:
    • aquaName is null OR
    • the contents of aquaName without the surrounding spaces in it result in an empty string

By Demorgan’s theorem, the passage occurs from the first to the second line, below:

NÃO (aquaName for nulo OU o conteúdo de aquaName sem os espaços circundantes nele não resultar numa string vazia) =

= NÃO (aquaName for nulo) E NÃO (o conteúdo de aquaName sem os espaços circundantes nele não resultar numa string vazia) =

= aquaName != null && !aquaName.getText().toString().isEmpty()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.