what is the difference of String between jdk7 and jdk8?

here i have the code below, I want to know why the same code produce different result in jdk7 and jdk8?

String s3 = new String("1") + new String("1");
System.out.println(System.identityHashCode(s3));    //JDK7 1485288136 - JDK8 985655350
String s3i = s3.intern();
System.out.println(System.identityHashCode(s3i));   //JDK7 1485288136 - JDK8 804611486
System.out.println(System.identityHashCode(s3));    //JDK7 1485288136 - JDK8 985655350
String s4 = "11";
System.out.println(System.identityHashCode(s4));    //JDK7 1485288136 - JDK8 804611486
System.out.println(s3 == s4); // JDK7 true - JDK8 false

CORRECT

Seems not because of JDK only, something about junit.

import org.junit.Test;

public class StringDemo {

    @Test
    public void test() {
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
        // JDK7 true - JDK8 false
    }

    public static void main(String[] args) {
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
        // JDK7 true - JDK8 true
    }

}

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You’re delving into implementation specifics of identityHashCode() and string interning that can, and do differ between various different versions. This behaviour is essentially undefined. FWIW, my Java 8 outputs this: 1829164700 1829164700 1829164700 1829164700 true …but that’s not guaranteed of course: identityHashCode() can differ whenever any of the internal object state differs, or the algorithm differs – both of these can change between versions. The value itself isn’t meaningful apart from being equal (or not) to another value generated in the same way. This is why the hashcodes are not equivalent across versions. intern() may not behave exactly the same… Read more »