When should we use intern method of String on String literals

后端 未结 14 810
生来不讨喜
生来不讨喜 2020-11-22 08:11

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string

14条回答
  •  情话喂你
    2020-11-22 08:46

    As you said, that string intern() method will first find from the String pool, if it finds, then it will return the object that points to that, or will add a new String into the pool.

        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = "Hello".intern();
        String s4 = new String("Hello");
    
        System.out.println(s1 == s2);//true
        System.out.println(s1 == s3);//true
        System.out.println(s1 == s4.intern());//true
    

    The s1 and s2 are two objects pointing to the String pool "Hello", and using "Hello".intern() will find that s1 and s2. So "s1 == s3" returns true, as well as to the s3.intern().

提交回复
热议问题