標籤:string常量池
面試題:String到底建立了幾個?
String s1 = new String("hello");String s2 = new String("hello");/** * s1建立了兩個對象,new String在堆中,然後引用著在常量池中建立"hello"地區。 * 而s2,只建立一個對象,就是堆的new String();因為常量池已有hello存在,所以便直接引用 */System.out.println(s1==s2);//false;System.out.println(s1.equals(s2));//true System.out.println("*************************");String s3 = new String("hello");String s4 = "hello";System.out.println(s3==s4);//falses3引用著堆,在引用著在常量池建立的"hello",s4 直接引用的已在常量池存在的hello,但它們地址值不相同。System.out.println(s3.equals(s4));//trueSystem.out.println("*************************");String s5 = "傳智";String s6 = "傳智";System.out.println(s5==s6);//true //當s6賦值時,發現常量池中有"傳智",就直接引用了它。所以s5與s6指向同一個地址值。System.out.println(s5.equals(s6));//trues5.substring(0, 1);//截取字元,是沒有修改s5的值,而是將截取的值,又在常量池中開闢一塊空間儲存。目前沒有被變數所引用。System.out.println(s5.equals(s6));//true System.out.println("*************************");
String常量池