Java中的字符串 == 比較, 內存分配

/**
 *  重溫一下
 */
public class StringMemoryTest {

    public static final String j = "123";
    public static final String k = "456";

    /**
     *
     * 對於那些在編譯時就能確定的****** 字面量*****都會存放在運行時常量池中,比如:

     字面量指的類似下面這種定義方式, 編譯器能夠確定值的,都會放到常量池中。
     String c = "hello " + "world"; //JVM會將此代碼優化爲String c = "hello world";
     String d = "hello world";

     而如下代碼
     String b = a + "world";
     其中a是變量,在編譯時不能確定值,所以不會被放在運行時常量池中,而是在heap中重新new了一塊兒內存

     * @param args
     * @throws AWTException
     */
    public static void main(String[] args) throws AWTException {

        {

            String c = "123456";

            String a = "123";
            String b = "456";
            String d = a + b;
            String f = a + b;
            String g = "123"+"456";
            String h = a +"456";

            String l = j+k;
            String m = a+k;

            System.out.println(c == d);
            System.out.println(c == f);
            System.out.println(c == g);
            System.out.println(c == h);  // a是的變量, 編譯期間jvm確定不了h的值,所以不會被放在運行時常量池中,而是在heap中重新new了一塊兒內存。
            System.out.println(c == l);
            System.out.println(c == m);

            /**
             * 執行結果
             false
             false
             true
             false
             true
             false
             */

//            System.out.println(c.equals(d));
//            System.out.println(c.equals(f));
//            System.out.println(c.equals(g));

        }


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