前兩天面試問到了這個基礎點,一般項目用&&運算,&做位運算,有點模糊了,查了下,重新理一下
1)&和&&都可以用作邏輯與的運算符,表示邏輯與(and),當運算符兩邊的表達式的結果都爲true時,整個運算結果才爲true,否則,只要有一方爲false,則結果爲false。
2)&&還具有短路的功能,即如果第一個表達式爲false,則不再計算第二個表達式,例如,對於if(str != null &&!str.equals(“”))表達式,當str爲null時,後面的表達式不會執行,所以不會出現NullPointerException,如果將&&改爲&,則會繼續判斷是否equals,而實際上str是null,則拋NullPointerException異常。如下示例,If(x==33 & ++y>0) y會增長,If(x==33 && ++y>0)不會增長
int x = 22;
int y = 2;
if (x >= 33 && ++y > 0)
{
Console.WriteLine(y);
}
Console.WriteLine(y);
if (x >= 33 & y++ > 0)
{
Console.WriteLine(y);
}
Console.WriteLine(y);
Console.ReadKey();
3)&還可以用作位運算符,當&操作符兩邊的表達式不是boolean類型時,&表示按位與操作,我們通常使用0x0f來與一個整數進行&運算,來獲取該整數的最低4個bit位,例如,0x31 & 0x0f的結果爲0x01。