String的創建方法一般有如下幾種
1.直接使用""引號創建;
2.使用new String()創建;
3.使用new String("someString")創建以及其他的一些重載構造函數創建;
4.使用重載的字符串連接操作符+創建。
例1
String s1 = "sss111"; //此語句同上 String s2 = "sss111"; System.out.println(s1 == s2); //結果爲true |
例2
String s1 = new String("sss111"); String s2 = "sss111"; System.out.println(s1 == s2); //結果爲false |
例3
String s1 = new String("sss111"); s1 = s1.intern(); String s2 = "sss111"; System.out.println(s1 == s2); |
例4
String s1 = new String("111"); String s2 = "sss111"; String s3 = "sss" + "111"; String s4 = "sss" + s1; System.out.println(s2 == s3); //true System.out.println(s2 == s4); //false System.out.println(s2 == s4.intern()); //true |
例5
這個是The Java Language Specification中3.10.5節的例子,有了上面的說明,這個應該不難理解了
package testPackage; class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); } } class Other { static String hello = "Hello"; } package other; public class Other { static String hello = "Hello"; } |
輸出結果爲true true true true false true,請自行分析!
結果上面分析,總結如下:
1.單獨使用""引號創建的字符串都是常量,編譯期就已經確定存儲到String Pool中;
2.使用new String("")創建的對象會存儲到heap中,是運行期新創建的;
3.使用只包含常量的字符串連接符如"aa" + "aa"創建的也是常量,編譯期就能確定,已經確定存儲到String Pool中;
4.使用包含變量的字符串連接符如"aa" + s1創建的對象是運行期才創建的,存儲在heap中;
5.使用"aa" + s1以及new String("aa" + s1)形式創建的對象是否加入到String Pool中我不太確定,可能是必須調用intern()方法纔會加入。
還有幾個經常考的面試題:
1.
String s1 = new String("s1") ; String s2 = new String("s1") ; 上面創建了幾個String對象? 答案:3個 ,編譯期Constant Pool中創建1個,運行期heap中創建2個. |
2.
String s1 = "s1"; String s2 = s1; s2 = "s2"; s1指向的對象中的字符串是什麼? 答案: "s1"