Stirng緩存

參考    https://blog.csdn.net/wjzhang5514/article/details/70209403

 

 

package cache;

/**
 * Created by sxf on 2018/6/26.
 */
public class StringDemo {

    public static void main(String[] args) {
        String s1 = "stringdemo";//常量池中
        String s2 = new String("stringdemo");//堆中
        String s3 = "string";
        String s4 = "demo";
        String s5 = "string" + "demo";// 常量池,s5 的創建是先進行右邊表達式的字符串連接,然後纔對 s5 進行賦值。
                                      // 賦值的時候會搜索池中是否有 HelloWorld 字符串,若有則把 s5 引用指向該字符串,
                                      // 若沒有則在池中新增該字符串。顯然 s5 的創建是用了 s1 已經創建好的字面量,故 true
        String s6 = s3 + s4;//new String(s3 + s4)//堆中
        System.out.println(s1 == s2);//false  常量池中--堆中
        System.out.println(s1 == s5);//true    常量池中--常量池中
        System.out.println(s1 == s6);//false   常量池中--堆中
        System.out.println(s2 == s2.intern());//false  堆中--常量池中
        System.out.println(s1 == s6.intern());//true   常量池中--常量池中

        //解釋:https://blog.csdn.net/wjzhang5514/article/details/70209403
        //注意: String a = "stringdemo";//存在棧中
        //      String b = new String("stringdemo");//存在堆中
        
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章