/** * 重温一下 */ 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)); } } }