& and && can both be used as logical AND operators, representing logical conjunction (and). The entire result is true only when the results of the expressions on both sides of the operator are true; otherwise, if either side is false, the result is false.
&& also has a short-circuit feature, meaning that if the first expression is false, the second expression is not evaluated. For example, in the expression , when is null, the subsequent expression will not execute, so a NullPointerException will not occur. If you change && to &, it will throw a NullPointerException. In , will increment, while in , it will not increment.<pre><code class="language-java">if(str != null && !str.equals("")
<pre><code class="language-java">str
<pre><code class="language-java">If(x==33 & ++y>0)
<pre><code class="language-java">y
<pre><code class="language-java">If(x==33&& ++y>0)
& can also be used as a bitwise operator. When the expressions on either side of the & operator are not boolean types, & represents a bitwise AND operation. We typically use 0x0f to perform & operations with an integer to obtain the lowest 4 bits of that integer. For example, the result of is 0x01. Assuming , what is the result of ? What is the result of ? The former results in 1, while the latter results in 0!<pre><code class="language-java">0x31 & 0x0f
<pre><code class="language-java">x=7
<pre><code class="language-java">x&&8
<pre><code class="language-java">x&8
&& is the logical AND operator: a && b. The value is true only when both a and b are true.
& is the bitwise AND operator.
7 & 8
is equivalent to 00000111 & 00001000 = 00000000.
It performs AND operation bit by bit.
Some may think that 8 & 8 should be 1, but it returns 8 when executed. Why is that?
8 & 8
0000 1000
& 0000 1000
————
0000 1000
It is still 8.
Additionally, & is generally used as an address operator. For example, defining an array a[], &a points to the address of the first element of the array.
Author: 冰零分子
