This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

1. Background

At work, Le Le would discuss some technical problems with her colleagues. Today, her colleague raised a question

String s =" STR "and String s = new String(" STR ")Copy the code

What was the difference between them that made Joy feel like she didn’t know enough about Stting, so she was ready to rethink the String class

Ii. Beginning of Analysis

Simple questions are often complicated. Joy thought it was String. Let’s see why it’s simple and why it’s complicated. Start with the source code

  1. The source code

    public final class String implements java.io.Serializable, Comparable, CharSequence { /** The value is used for character storage. */ private final char value[];

    /** Cache the hash code for the string */ private int hash; /** Use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L; .Copy the code

    It’s a long class, but you must have seen final, and why you remember that, because when you’re interviewing, you’re going to be asked how many objects you add up. Is there any difference between String s =” STR “and String s = new String(” STR “)? You might say no, but there is. What the difference? String s =”ss” is put in the constant pool at compile time. String s = new String(” STR “) is put in the constant pool at run time. It does two things

  2. Code validation

String str5 = new String(" Yang ")+new String(" lele "); System.out.println(str5== str5.intern() ); //true String str6 = new String(" y "); System.out.println(str6== str6.intern() ); //falseCopy the code

(str6) {str6: String () {str6: String () {str6: String () {str6: String () {str6: String () {str6: String () {str6: String (); Intern () returns false if str6 refers to head and STR6. Intern () refers to constant pool. String str5 = new String(” Yang “)+new String(” lele “); Create a new “Yang” in the head and constant pool and create a “Le Le” in the head and constant pool. Eventually the STR5 becomes a reference to the new String (” Yang Le le “). Str6 == str6.intern() compares two references to the same, so returns true.

Then I told my colleague that there was a problem with the online answer, the online answer to the intern method. The purpose of the intern method in the String String is the current character object (the object that comes out of new) and you can use the intern method to get it from the constant pool, If the string does not exist in the constant pool, create a new one and place it in the constant pool. There is no reference in this. My colleague said this is the difference between JDK1.6 and JDK1.7.