How does intern work in the following code?

前端 未结 2 905
醉酒成梦
醉酒成梦 2021-01-19 02:43
String a = \"abc\";
String b = a.substring(1);
b.intern();
String c = \"bc\";
System.out.println(b == c);

The question might be foolish as intern h

相关标签:
2条回答
  • 2021-01-19 02:53

    String b = a.substring(1); returns string instance which contains "bc" but this instance is not part of string pool (only literals are by defaults interned, string created via new String(data) and returned from methods like substring or nextLine are not interned by default).

    Now when you invoke

    b.intern();
    

    this method checks if String Pool contains string equal to one stored in b (which is "bc") and if not, it places that string there. So sine there is no string representing "bc" in pool it will place string from b there.

    So now String pool contains "abc" and "bc".

    Because of that when you call

    String c = "bc";
    

    string literal representing bc (which is same as in b reference) will be reused from pool which means that b and c will hold same instance.

    This confirms result of b==c which returns true.

    0 讨论(0)
  • 2021-01-19 03:13

    Look at the doc of String#intern() method

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Now follow the comments

        String b = a.substring(1);  // results "bc"
        b.intern();                 // check and places "bc" in pool
        String c = "bc";            // since it is a literal already presented in pool it gets the reference of it
        System.out.println(b == c);// now b and c are pointing to same literal
    
    0 讨论(0)
提交回复
热议问题