String的常量池

 1 package day01;
 2 /**
 3  * String的常量池
 4  * JVM在堆中开辟了一段空间迎来缓存所有使用字面量
 5  * 创建的字符串对象.只要发现使用已经创建过的字符串
 6  * 字面量创建新字符串时,JVM会直接使用缓存的对象,
 7  * 而不是再创建新对象.这样做可以避免内存中堆积大量
 8  * 内容一样的字符串对象,降低内存开销.
 9  * @author ta
10  *
11  */
12 public class Demo2 {
13     public static void main(String[] args) {
14         //直接量 字面量
15         String s1 = "123abc";
16         String s2 = "123abc";//重用s1创建的对象
17         String s3 = "123abc";//一样重用
18         
19         System.out.println(s1==s2);//true
20         System.out.println(s1==s3);//true
21         
22         //一旦修改内容,就会创建新对象
23         s1 = s1+"!";//s1不再指向原对象
24         System.out.println("s1:"+s1);
25         System.out.println("s2:"+s2);
26         
27         //new是一个比较强制的操作,一定创建新对象
28         String s4 = new String("123abc");
29         System.out.println("s4:"+s4);
30         System.out.println(s2==s4);//false
31         
32         /*
33          * 这里触发了编译器的一个特点:
34          * 编译器在编译源代码时若发现一个计算表达式
35          * 参与的值都是字面量时,那么该计算表达式的
36          * 结果是确定的,此时编译器就会计算表达式的
37          * 结果,并将结果替换这个表达式.这样一来JVM
38          * 每次执行字节码文件时就不用计算了.
39          * 下面的代码会被编译器编译后改为:
40          * String s5 = "123abc";
41          */
42         String s5 = "123"+"abc";
43         System.out.println("s5:"+s5);
44         System.out.println(s2==s5);//true
45         
46         String s = "123";
47         String s6 = s + "abc";//修改内容创建新对象
48         System.out.println("s6:"+s6);
49         System.out.println(s2==s6);//false
50         
51         
52 
53         
54     }
55 }

猜你喜欢

转载自www.cnblogs.com/yinxiangjinan/p/11123588.html
今日推荐