JAVA字符串编译期优化

public class StrABCD {

    static    String ss = "ABCD";

    public static void main(String[] args) {
        
        String s1 = "ABCD";
        
        String s2 = "A"+"B"+"C"+"D";
        
        String s3 = "AB"+"CD";
        
        String s4 = new String("ABCD");
        
        String t  = "AB";
        
        String s5 = t+"CD";
        
        
        System.out.println(ss == s1);//true
        System.out.println(s1 == s2);//true
        System.out.println(s1 == s3);//true
        System.out.println(s1 == s3);//true
        System.out.println(s2 == ss);//true
        System.out.println(s3 == ss);//true
        System.out.println(s1 == s4);//false
        System.out.println(s1 == s5);//false
        
        String analyze ="1、s1 == s2 因为在编译期间就做了编译优化,"
                + "运行时,先在常量池中查找,如果找到ABCD就直接把地址给s1拷贝一份"
                + "2、s2 运行时直接拷贝s1的地址,因为已经存在"
                + ""
                + "3、ss == s1  ss是静态属性,优先加载,并在常量池创ABCD字符串"
                + ""
                + "4、s1 在方法区中的常量池,s4在堆中 必然不等"
                + ""
                + "5、s5通过反编译文件查看到底层是使用StringBuilder的append方法添加";
        
        //反编译源码赏析:
        
//        import java.io.PrintStream;
//
//        public class StrABCD
//        {
//
//            static String ss = "ABCD";
//
//            public StrABCD()
//            {
//            }
//
//            public static void main(String args[])
//            {
//                String s1 = "ABCD";
//                String s2 = "ABCD";
//                String s3 = "ABCD";
//                String s4 = new String("ABCD");
//                String t = "AB";
//                String s5 = (new StringBuilder(String.valueOf(t))).append("CD").toString();
//                System.out.println(ss == s1);
//                System.out.println(s1 == s2);
//                System.out.println(s1 == s3);
//                System.out.println(s1 == s3);
//                System.out.println(s2 == ss);
//                System.out.println(s3 == ss);
//                System.out.println(s1 == s4);
//                System.out.println(s1 == s5);
//                String analyze = "1、s1 == s2 因为在编译期间就做了编译优化,运行时,先在常量池中查找,如果找到ABCD就直接把地址给s1拷贝一份2、s2 运行时直接拷贝s1的地址,因为已经存在3、ss == s1  ss是静态属性,优先加载,并在常量池创ABCD字符串4、s1 在方法区中的常量池,s4在堆中 必然不等5、s5通过反编译文件查看到底层是使用StringBuilder的append方法添加";
//            }
//
//        }
        

    }
}




有错误之处,请指出,本人万分感激。。。。。。。。。。。。。。。。

 

posted @ 2018-05-13 20:53  马鞍山  阅读(455)  评论(0编辑  收藏  举报