What is the difference between "& & "between" & " and "| | "between" | " java?

Read the book the philosophy of Java. got to the point: enter a description of the image here what is the difference between single and double use of sivvols

boolean i,a;
if(a||i){}
if(a|i){}

if(a&&i){}
if(a&i){}

Except that & it should beat two true, and with |, you only need one true.

1 answers

In general, & and | are bitwise operators, while && and || are logical operators.

In the case of boolean types, there is no fundamental difference in your example. In general, when using & or | on boolean, the right side of the expression will be evaluated regardless of what value the left side of the expression has.

For example, if there were not just variables, but a method, say:

private boolean additionalCheck() {
    // делаем что-то
    // к примеру, меняем глобальное состояние
    return true;
}

Then there will be a difference between if(a||additionalCheck()){} and if(a|additionalCheck()){} if a is equal to true.

In the first case, additionalCheck() will not be called at all, because a is already true and there is no point in checking other conditions. But in the second case, additionalCheck() will be called regardless of the value of a.

If you have specific logic in additionalCheck(), for example, changing the global state, then you need to choose wisely what to use - |/& or ||/&&.

 3
Author: Suvitruf - Andrei Apanasik, 2019-01-30 19:49:55