The differences of these four operators can be easily distinguished by name:|| (short circuit or), | (or),&& (short circuit and),& (bitwise AND) are explained by a simple example:
public class Test1 {public static void Main (string[] args) { int i=0; if (3>2 | | (i++) >0) { System. Out. println (i);}} }
The I value of this program output is 0the reason is | | At the time of judgment, if the previous judgment is true, then it is no longer judged whether the subsequent statement is true, then the subsequent statement will not be executed.
If you will | | What would the result be?
public class Test1 {public static void Main (string[] args) { int i=0; if (3>2 | (i++) >0) { System. Out. println (i);}} }
The result output I is a value of 1,The reason is that when the operator makes a judgment, regardless of whether the previous expression is true or not, it executes the following statement, then the value of I is added 1 to 1.
public class Test2 {public static void Main (string[] args) { //TODO auto-generated method stub int i=0; if (i++>2 && (i++) >2) { system. Out. println ("i=" +i), } else { system. Out. println (i);
} }}
the value of the result output I is 1The reason is that when the && operator is making a judgment, when the first expression is false, it will directly determine that the entire expression is false and the subsequent statement will not be executed.
switch && to &
public class Test2 {public static void Main (string[] args) { //TODO auto-generated method stub int i=0; if (I++>2 & (i++) >2) { system. Out. println ("i=" +i), } else { system. Out. println (i); } }}
result output I has a value of 2the reason is that & will compare the results of the expression before and after, so it will output 2.
in Java | | The difference between |,&& and &