java中String對象的存儲位置
轉載注明出處:https://www.cnblogs.com/carsonwuu/p/9752949.html
本次樣例中使用6個test直接演示String對象的創建位置:堆、棧、常量池。
1 package test.string.equal; 2 3 public class Main { 4 5 /** 創建了三個對象,"helloworld對象創建在常量池中",每次new String()都會創建一個對象在堆內存中工兩個堆對象。 6 * 7 */ 8 void test() { 9 String s1= new String("helloworld"); 10 String s2= new String("helloworld"); 11 } 12 /**程序只創建一個字符串對象“Java”,存放在常量池中,所以s1==s2 為true 13 * 14 */ 15 void test1(){ 16 String s1="Java"; 17 String s2="Java"; 18 System.out.println(s1==s2); 19 } 20 21 /** 第一個new String("Java"):創建了兩個對象,Java創建於常量池中,String對象創建於堆內存中。 22 * 第二個new String("Java"):由於常量池中有Java對象,所以只需創建一個對象,String對象創建於堆內存中。 23 * s1與s2分別指向String對象堆內存,所以s1==s2 為false 24 */ 25 void test2() { 26 String s1=new String("Java"); 27 String s2= new String("Java"); 28 System.out.println(s1==s2); 29 } 30 31 /** 常量的值在編譯的時候就確定了,"hello"、"world"都是常量,因此s2的值在編譯的時候也確定了, 32 * s2指向常量池中的"hello world",所以s1==s2為true 33 * 34 */ 35 void test3() { 36 String s1="hello world"; 37 String s2="hello "+"world"; 38 System.out.println(s1==s2); 39 } 40 41 /** s4由兩個String變量相加得到,不能再編譯時就確定下來,不能直接引用常量池中的"helloworld"對象,而是在堆內存中創建一個新的String對象並由s4指向 42 * 所以s1==s4為false 43 * 44 */ 45 void test4() { 46 String s1="helloworld"; 47 String s2="hello"; 48 String s3="world"; 49 String s4=s2+s3; 50 System.out.println(s1==s4); 51 } 52 53 /** s2與s3被final修飾為宏變量,不可更改,編譯器在程序使用該變量的地方直接使用該變量的值進行替代,所以s4的值在編譯的時候就為"helloworld" 54 * 指向常量池中的"helloworld"對象 55 * 所以s1==s4為true 56 * 57 */ 58 void test5() { 59 String s1="helloworld"; 60 final String s2="hello"; 61 final String s3="world"; 62 String s4=s2+s3; 63 System.out.println(s1==s4); 64 } 65 public static void main(String[] args) { 66 Main o = new Main(); 67 o.test1(); 68 o.test2(); 69 o.test3(); 70 o.test4(); 71 o.test5(); 72 73 } 74 }
