1. 比較運算符 “==”
如果進行比較的兩個操作數(shù)是數(shù)值型的,則是比較兩個操作數(shù)的值,只有二者的值相等,就返回true.
如果進行比較的是引用類型,則當二者都執(zhí)行相同的實例時,才返回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,但由于兩個分別是不
同的對象實例對象,在堆內(nèi)存中占有不同的內(nèi)存空間,所以str1 == str2返回false.當執(zhí)行str3 = "123"時,系
統(tǒng)會先從緩存中檢查是否有一個內(nèi)容為"123"的實例存在,如果沒有則會在緩存中創(chuàng)建一個String對象"123",
執(zhí)行str4 = “123”時,緩存中已經(jīng)有了相同內(nèi)容的對象,系統(tǒng)則不再生成對象,直接將str4指向那個對象.所
以str3 == str4會返回true.
同樣的系統(tǒng)會把一些創(chuàng)建成本大,需要頻繁使用的對象進行緩存,從而提高程序的運行性能.再比如
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
}
}
系統(tǒng)會將int整數(shù)自動裝箱成Integer實例,新建實例時,系統(tǒng)會先創(chuàng)建一個長度為256的Integer數(shù)組,
其中存放-128到127的Integer實例,當再需要一個在這個范圍中的Integer對象時,系統(tǒng)會直接將引用變量
指向相應(yīng)的實例對象,ia和ib都指向相同的Integer對象所以上面的ia == ib 返回true;而當需要創(chuàng)建的
Integer對象不在這個范圍中時,系統(tǒng)則會新創(chuàng)建對象,實際上ic和id是兩個不同的對象,則ic == id 返回false.
2. 邏輯運算符
程序清單:|| 和 | 的區(qū)別
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
}
}
}
"||" 當前面的結(jié)果為true時,不會在計算后面的結(jié)果,會直接返回true;"|"總是會計算前后兩個表達式.