1. 比較運算符 “==”
如果進行比較的兩個操作數是數值型的,則是比較兩個操作數的值,只有二者的值相等,就返回true.
如果進行比較的是引用類型,則當二者都執行相同的實例時,才返回true.
程序清單:String類型的比較
public class StringTest {
public static void main(String[] args) {
String str1 = new String("123");
String str2 = new String("123");
System.out.println(str1 == str2);//這里返回false
System.out.println(str1.equals(str2));//true
String str3 = "123";
String str4 = "123";
System.out.println(str3 == str4);//這里返回true
System.out.println(str3.equals(str4));//true
}
}
如代碼所示,兩個new得到的String對象雖然值相等,str1.equals(str2)返回true,但由于兩個分別是不
同的對象實例對象,在堆內存中占有不同的內存空間,所以str1 == str2返回false.當執行str3 = "123"時,系
統會先從緩存中檢查是否有一個內容為"123"的實例存在,如果沒有則會在緩存中創建一個String對象"123",
執行str4 = “123”時,緩存中已經有了相同內容的對象,系統則不再生成對象,直接將str4指向那個對象.所
以str3 == str4會返回true.
同樣的系統會把一些創建成本大,需要頻繁使用的對象進行緩存,從而提高程序的運行性能.再比如
Integer類.
程序清單,Integer的比較
public class IntegerTest {
public static void main(String[] args) {
Integer ia = 1;
Integer ib = 1;
System.out.println(ia == ib); //true
Integer ic = 128;
Integer id = 128;
System.out.println(ic == id); //false
}
}
系統會將int整數自動裝箱成Integer實例,新建實例時,系統會先創建一個長度為256的Integer數組,
其中存放-128到127的Integer實例,當再需要一個在這個范圍中的Integer對象時,系統會直接將引用變量
指向相應的實例對象,ia和ib都指向相同的Integer對象所以上面的ia == ib 返回true;而當需要創建的
Integer對象不在這個范圍中時,系統則會新創建對象,實際上ic和id是兩個不同的對象,則ic == id 返回false.
2. 邏輯運算符
程序清單:|| 和 | 的區別
public class LogicTest {
public static void main(String[] args) {
int a = 1;
int b = 2;
if (a == 1 || b++ == 3) {
System.out.println("a="+a+",b="+b);//a=1,b=2
}
if (a == 1 | b++ ==3) {
System.out.println("a="+a+",b="+b);//a=1,b=3
}
}
}
"||" 當前面的結果為true時,不會在計算后面的結果,會直接返回true;"|"總是會計算前后兩個表達式.