package com.bjpowernode.demo01;
/**
* String字符串對象是不可變的
* @author Administrator
*
*/
public class Test04 {
public static void main(String[] args) {
String s1 = "hello";
s1 = "world";
byte[] bytes = {65,66,67,97,98,99};
String s2 = new String(bytes);
s2 = s2 + "hehe";
/*
* 在字符串連接時, 會使用StringBuilder類創建對象,進行字符串的連接,
* 最後生成一個新的String對象賦值給s2變量
*/
}
}
內存分析圖:
package com.bjpowernode.demo01;
/**
* String對象不可變的,每次進行字符串連接都會生成新的字符串對象
* @author Administrator
*
*/
public class Test05 {
public static void main(String[] args) {
//以下兩行共創建了多少個String對象? 3個: "abc"是一個, 堆區中創建了兩個
String s1 = new String("abc");
String s2 = new String("abc");
//在創建s1對象時, 使用到"abc"字面量, 保存到字符串常量池中
//以後再使用"abc"字面量時, 就直接把常量池中的"abc"對象的引用給返回
String s3 = "abc";
String s4 = "abc";
//s3和s4都是引用了常量池中的同一個"abc"常量
System.out.println( s3 == s4 ); // true
//以下兩行共創建了多少個String對象? 兩個 : "hello"字面量, "hellohello"連接生成一個新的
String s5 = "hello";
String s6 = s5 + "hello";
//以下兩行共創建了多少個String對象? 三個: "hehe", "he", "hehehehe"
String s7 = "hehe";
String s8 = s7 + "he" + "he";
//以下兩行共創建了多少個String對象? 兩個: "haha" , "hahahaha"
String s9 = "haha";
String s10 = "ha" + "ha" + s9; //當前編譯器會進行優化, 把"ha" + "ha"優化爲"haha"
}
}