String s =new String()分析堆與棧

先定義S

1. String str1 = "abc"; 
  System.out.println(str1 == "abc"); 

步驟: 
1) 棧中開闢一塊空間存放引用str1, 
2) String池中開闢一塊空間,存放String常量"abc", 
3) 引用str1指向池中String常量"abc", 
4) str1所指代的地址即常量"abc"所在地址,輸出爲true 

2. String str2 = new String("abc"); 
  System.out.println(str2 == "abc"); 

步驟: 
1) 棧中開闢一塊空間存放引用str2, 
2) 堆中開闢一塊空間存放一個新建的String對象"abc", 
3) 引用str2指向堆中的新建的String對象"abc", 
4) str2所指代的對象地址爲堆中地址,而常量"abc"地址在池中,輸出爲false 

3. String str3 = new String("abc"); 
  System.out.println(str3 == str2); 

步驟: 
1) 棧中開闢一塊空間存放引用str3, 
2) 堆中開闢一塊新空間存放另外一個(不同於str2所指)新建的String對象, 
3) 引用str3指向另外新建的那個String對象 
4) str3和str2指向堆中不同的String對象,地址也不相同,輸出爲false 

4. String str4 = "a" + "b"; 
  System.out.println(str4 == "ab"); 

步驟: 
1) 棧中開闢一塊空間存放引用str4, 
2) 根據編譯器合併已知量的優化功能,池中開闢一塊空間,存放合併後的String常量"ab", 
3) 引用str4指向池中常量"ab", 
4) str4所指即池中常量"ab",輸出爲true 

5. final String s = "a"; 
  String str5 = s + "b"; 
  System.out.println(str5 == "ab"); 

步驟: 
同4 

6. String s1 = "a"; 
  String s2 = "b"; 
  String str6 = s1 + s2; 
  System.out.println(str6 == "ab"); 

步驟: 
1) 棧中開闢一塊中間存放引用s1,s1指向池中String常量"a", 
2) 棧中開闢一塊中間存放引用s2,s2指向池中String常量"b", 
3) 棧中開闢一塊中間存放引用str5, 
4) s1 + s2通過StringBuilder的最後一步toString()方法還原一個新的String對象"ab",因此堆中開闢一塊空間存放此對象, 
5) 引用str6指向堆中(s1 + s2)所還原的新String對象, 
6) str6指向的對象在堆中,而常量"ab"在池中,輸出爲false 

7. String str7 = "abc".substring(0, 2); 
  
步驟: 
1) 棧中開闢一塊空間存放引用str7, 
2) substring()方法還原一個新的String對象"ab"(不同於str6所指),堆中開闢一塊空間存放此對象, 
3) 引用str7指向堆中的新String對象, 

8. String str8 = "abc".toUpperCase(); 
  
步驟: 
1) 棧中開闢一塊空間存放引用str6, 
2) toUpperCase()方法還原一個新的String對象"ABC",池中並未開闢新的空間存放String常量"ABC", 
3) 引用str8指向堆中的新String對象

    public void hello(){
        String hello="hello";
        String hel="hel";
        String lo="lo";
        System.out.println(hello=="hel"+"lo");
        System.out.println("hello"=="hel"+"lo");
        System.out.println("hello"=="hel"+lo);
        System.out.println("hello"==hel+lo);
        System.out.println(hello==hel+lo);

    }

true
true
false
false
false

    @Test
    public void String(){
        String abc="abc";
        System.out.println(abc=="abc");//true
        String a="";
        String b="";
        System.out.println(a==b);//true
    }




引用:http://zhidao.baidu.com/link?url=L1YfaYRaQ_dkRRn8FFRPUkiTI3Z0-x-HzttZKfeU7d_5AZJ8ohyzvu_QcGnSB5Jmy-fLzcMQTdnYQIfmiWIWOa
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章