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

Question:

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

Questions

  • What is the difference between the & and && operators?
  • What is the & operator for?
  • An example usage for the & ?
  • What is the difference between the operators | and || ?
  • What is the operator for | ?
  • An example usage for the operator | ?

Answer:

The difference between the logical operators that use one symbol and two symbols is that when you use two, it is known as short-circuit logical operators .

The short-circuit logical operator executes as little code as possible in order to process the logic operation, that is, if you are doing a comparison of type if(false && true) when processing this piece and find that right away the first result is false it it doesn't even parse the second part of the logic, so it doesn't matter if the second part is true or false , because false && qualquerCoisa always returns false .

In general, short-circuit logical comparators are always used as they will never be slower than non-short-circuit logical 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 on Ideone

In the first case, as it is a short circuit, it does the first ++a , checks that it is greater than 5 and does not continue executing the code after the || , because true OU qualquerCoisa is true . As if(true) it enters the if and does a++ , making it 7 .

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

Scroll to Top