The relationship and difference between & and && in Java logical operators

First of all, & (logical AND) and && (short-circuit AND) are both logical operators in the Java language. From the perspective of the final operation results of & and &&, there is no difference between the two.
In fact, the logical operators & and && both mean "logical AND", so what is the difference between them? In terms of the operating rules of these two operators, only if the results of the expressions on both sides of the operator are true, then the result after the "logical AND" is true, and all other cases are false. Using the logical operator "&" will judge the expressions on both sides; while the operator "&&" will determine whether the expression on the other side will be executed based on the result of the expression on one side. When the first expression is false When the second expression is not judged, it is equivalent to directly shielding the execution of the second expression, and directly output the result to save the number of computer judgments. Usually the value of the whole expression that can be inferred from the left end of the logical expression is called "short-circuit", and those expressions that always execute both sides of the logical operator are called "non-short-circuit". It can be seen that "&&" is a short-circuit operator, and "&" is a non-short-circuit operator, and it is obvious that the execution efficiency of "&&" is higher than that of "&".
for example:

int x=1;
int y=2;
boolean b1 = (x>y)&(x>y++);//执行结束后y的值为3
//boolean b2 = (x>y)&&(x>y++);//执行结束后y的值仍为2
System.out.println(y);

The above content is a bit of personal learning experience. If there are errors in the knowledge points, please leave a message to remind you, if there is any infringement content reminder, delete it immediately.

Guess you like

Origin blog.csdn.net/pf6668/article/details/107305862