細節問題1:你還記得String字面量賦值與非字面量賦值過程嗎?
package java基礎;
public class String_Test {
public static void main(String[]args){
String a1 = "123";//字面量賦值,由虛擬機創建對象存儲在方法區的運行常量池
String b1 = "123";//查找運行常量池是否有該內容,然後直接棧中創建b1指向該地址
System.out.println("a1==b1?"+(a1==b1)+" a1="+a1+" b1="+b1);//所有a1地址等於b1
//String是不可變字符串指的是值不能改變,但是我們使用字面量重賦值相當於修改地址
a1 = "hello";
b1 = "hello";
System.out.println(a1==b1);//地址引用修改相同,都是指向常量池裏邊的hello
//
String a2 = new String("hello");
System.out.println(a1==a2);//比較地址引用,有new就是在堆區開闢了內存,地址引用不同,false
//修改一下a2,然後使得
String b2 = a1+"hello";//只有有一個不是字面量,都會使用new,b2 = ”hellohello“,b2的值在堆區
a1 = "hellohello";
System.out.println(b2+" "+a1);
System.out.println(a1==b2);//因爲b2用了new,那麼必然在堆區開闢內存,則地址引用必然不同,false
String b3 = b2;//不是字面量,就用來new
System.out.println(b3==b2);//地址引用就不同,都是在堆區,則==比較內容 true
System.out.println(b3==a1);//比較地址引用,不同 false
System.out.println("______________________________");
}
}
小夥伴們,你答對了幾個呢?