What is the difference and what are operators & and && e | and || in Java for?

Asked

Viewed 14,617 times

22

I was analyzing some possibilities for the implementation of an algorithm and I went to look up this & and |, and I read some topics in English but it’s not 100% clear to me what it’s for and where I can use it. Then I would like an explanation, clearer and with practical examples of how to use it. (And in my native language, in case: Português).

Questions

  • What is the difference between operators & and &&?
  • What is the operator for &?
  • An example of use for the operator &?
  • What is the difference between operators | and ||?
  • What is the operator for |?
  • An example of use for the operator |?
  • 3

    Maybe here will be a complete answer on the 4 operators, but for now, this one responds well on the use of | and ||.

  • 1

    The "double" version would be to manipulate integer values, the "single" version for bit-by-bit logic.

  • Tip: Make Codecademy Javascript Curse that you get it in a flash (:

  • 2

    @bpinhosilva not always, see my answer :)

  • Right, @Math, but what I meant is that the & operator does the logical execution on the operating bits instead of && that does it on the actual value of the operands.

  • @bpinhosilva the & can also make the comparison in the truth value of operands, say that the & only makes the logic in bit a bit is wrong.

  • @Math, maybe my expression wasn’t complete, there’s the difference you quoted in your answer and it’s explained well. I said it’s mostly used for bit-by-bit operation, I didn’t mean it would be "just" for it.

Show 2 more comments

2 answers

19

& is a binary operation, see more on Wikipedia - Binary logic, Example:

int a = 60; // Em binário, 60 é 0011 1100
int b = 13; // Em binário, 13 é 0000 1101
int c = a & b; // Complicado, mas quando os dois dígitos forem 1, o resultado será 1, se não será 0. Ou seja, "c" dará 0000 1100, que é 12.

&& means "and", or "and", for example:

if (1 == 1 && 6 > 9) {
    // Se 1 for igual a 1 E 6 for maior que 9, isso vai acontecer, no caso não, pois 6 não é maior que 9.
}

| is another binary operation, where if any of the binary digits are 1, the result will be one, example:

int a = 60; // Em binário, 60 é 0011 1100
int b = 13; // Em binário, 13 é 0000 1101
int c = a | b; // Quando um dos dígitos forem 1, o resultado será 1 também. "c" dará 0011 1101, que é 61.

|| means "or", or "or", for example:

if (1 == 1 || 6 > 9) {
    // Se 1 for igual a 1 OU 6 for maior que 9, isso vai acontecer, no caso sim, pois 1 é igual a 1, e isso já basta para o |.
}

19


The difference between the logical operators that use a symbol and two symbols is that when you use two is what is known as logic short circuit operators.

The logic short-circuit operator performs as little code as possible in order to process the logical operation, i.e., if you are making a comparison of the type if(false && true) when processing this part and find that soon the first result is false he does not even analyze the second part of logic, so it does not matter if the second part is true or false, for false && qualquerCoisa always gives false.

In general, short-circuit logic comparators are always used, as they will never be slower than non-short-circuit logic operators. However it is necessary to be aware of exceptional situations where the execution or not of the rest of the operators can change the program flow and generate an unexpected result, such as:

int a = 5;
if(++a > 5 || ++a > 6) a++; 
System.out.println(a);       //a==7

Against:

int b = 5;
if(++b > 5 | ++b > 6) b++; 
System.out.println(b);       //b==8

Example in Ideone

In the first case, for being a short circuit he makes the first ++a, checks that it is greater than 5 and does not continue to execute the code after the ||, for true OU qualquerCoisa is true. How did you give if(true) he enters the if and makes a++, making it 7.

In the second case, by not using short circuit operators it processes everything that is within the if, soon he makes ++b twice, resulting in if(true|true) which is the same thing as if(true), it enters the code inside the if and does b++ making it 8.

  • 2

    Despite the reply by Tiago Porsch, be quite clear and explanatory, he did not mention this behavior of binary operators in ifs of booleans, as the logical operators (&& and ||), that was one of my main doubts when posting the question. So that would be the only difference of using one or the other in a conditional if of booleans (Understand "if of booleans" as an example: if(valor1 > valor2 & valor3 < valor4) and/or if(valor1 > valor2 && valor3 < valor4))?

  • 1

    Yes, the only difference is the smaller path to follow when using short circuit operators. I focused on boleanas operations because first that Porsch did not mention, and then because when asking the differences of & and && I led to believe that although the binary operation was interesting it was not the focus, because the && never serves that purpose.

  • Perfect Math, maybe it’s also because you didn’t specify this in the question, but it’s not a problem, because then the answers become more complete, and comprehensive. And there are also some things there that I didn’t even know (about binary operations).

  • 1

    Yes, of course, there was no way you could specify something you didn’t know, rs.. Either way the two answers cover the total operators you quoted, and that’s good, in my opinion.

Browser other questions tagged

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