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