java8 str.intern() 测试

package io.openmessaging.storage.dledger;

public class T {

    public static void main(String[] args) {
        /* 
         * String str = new String("a"); //产生常量a ,堆上的new String
         * str = str.intern();   //找到常量池的a
         * 
         * String str2 = "a"; //常量池中的a
         * 
         * System.out.println(str == str2);
         */

        /*String s5 = new String("hi") + new String("j");

        s5.intern();

        String s6 = "hij";

        // s5 == s6 ? true
        System.out.println(String.format("s5 == s6 ? %s", s5 == s6));*/
        
        
        String s5 = new String("hi") + new String("j"); //产生两常量hi,j  堆上的new String

        s5.intern(); //将s5的引用加入常量池

        String s6 = "hij";//s6指向s5
        s6 = s6.intern();

        // s5 == s6 ? true
        System.out.println(String.format("s5 == s6 ? %s", s5 == s6));
        
        String s7 = new String("hij");
        s7 = s7.intern();
        System.out.println(String.format("s5 == s6 ? %s", s5 == s7));
        
        
        
        
        String s = "zzn" + 2L;
        String s2 = "zzn" + 2L;

        System.out.println(s == s2);
        
        

        String s3 = "zzn" + 222222L;
        String s4 = "zzn" + 222222L;

        System.out.println(s3 == s4);
        
        System.out.println(add(44444L) == add(44444L));
        System.out.println(add2(44444L) == add2(44444L));
    }
    
  
    public static String add(Long l) {
        return "zz"+l;
    }
    
    public static String add2(Long l) {
        return ("zz"+l).intern();
    }

}


s5 == s6 ? true
s5 == s6 ? true
true
true
false
true

总结:

jdk1.6:

str.intern()返回常量池对象

jdkl1.8:

str.intern();

当str是常量String  str="a”,此时常量池中不存在常量或者引用,那么将常量“a”加入常量池。如果常量池中存常量或者引用,那么str指向常量池中的常量或者引用。

当str是指向堆中的引用String  str=new String("hi") + new String("j"),此时常量池中不存在常量或者引用,那么将常量“hij”得引用str加入常量池。 如果常量池中存常量或者引用,那么str指向常量池中的常量或者引用。

常量池只会保留一份,要么是常量,要不是指向堆中的引用

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0