The difference between & and && in Java

The difference between & and && in Java?

1. Both & and && can be used as logical AND operators, which means logical and (and). When the results of the expressions on both sides of the operator are true, the entire operation result is true, otherwise, as long as one of them is false , The result is false.

2.&& also has a short-circuit function (short-circuit and), that is, if the first expression is false, the second expression is no longer calculated, for example, for if(str!=null &&!str.equals("" )) expression. When str is null, the following expression will not be executed, so NullPointerException will not occur. If you change && to &, a NullPointerException will be thrown.

如果int x=33 那么 
If((x==33)& (++y>0))    y会增长, 
If((x==33)&&(++y>0))  y不会增长 

3.& can also be used as a bit operator. When the expression on both sides of the & operator is not boolean type, & means bitwise AND operation. We usually use 0x0f to perform & operation with an integer to get the lowest 4 of the integer Bits, for example, the result of 0x31&0x0f is 0x01.

Guess you like

Origin blog.csdn.net/qq_40694640/article/details/112968943