0

when I run this program in jdk8 and jdk17, the result is different.

    public class StringIntern {
    public static void main(String[] args) {

        String s = new String("1");
        s.intern();
        String s2 = "1";
        System.out.println(s == s2);//jdk6:false   jdk7/8:false

       
        String s3 = new String("1") + new String("1");//pos_1
        s3.intern();

        String s4 = "11";
        System.out.println(s3 == s4);//jdk6:false  jdk7/8:true


    }
}

JDK8: false true

JDK17: false false

Can you tell me why? Thanks a lot.

  • A pooled string `s3` (`s3.intern();`) and a string literal will always be represented by the same object. – Alexander Ivanchenko Mar 08 '22 at 15:00
  • What is the specific problem you're trying to address? You shouldn't be using double equals anyway to compare strings – OneCricketeer Mar 08 '22 at 15:01
  • @OneCricketeer I try to find the deep reason about StringTable. My purpose is comparing the menory address different or the same, not string value. – Jueheng Xie Mar 08 '22 at 15:11
  • String is immutable - you must assign the return value of `intern()` to another variable, intern has no effect on the current instance. Most likely the jdk17 compiler has spotted that s3 is constant and has evaluated it, hence it is same literal as s4. – DuncG Mar 08 '22 at 15:24
  • 2
    Can’t reproduce with my installations of JDK 17. But there might be something in your environment causing the string `"11"` to be in memory already. – Holger Mar 09 '22 at 15:25

0 Answers0