How does intern work in the following code?

前端 未结 2 927
醉酒成梦
醉酒成梦 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 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
    

提交回复
热议问题