String intern() behaviour

前端 未结 4 897
借酒劲吻你
借酒劲吻你 2020-12-11 11:27

From the javaDocs of String class\'s intern method :

When the intern method is invoked, if the pool already contains a string equal to this String o

4条回答
  •  暖寄归人
    2020-12-11 12:01

    pczeus is correct. More info:

    fifth is a new string (pool was not checked) that contains the value "Hello". When you intern() it, the return value is fourth (first occurrence of "Hello" being interned), which does not equal fifth.

    Same answer for sixth.

    seven is the first occurrence of "Hello2" and it does not get interned until you call 'seven == seven.intern()'. Since it gets interned at that moment the return value of intern() is seven.

    eight is another new instance of "Hello2". When it gets interned, the return value is seven, which is not eight

提交回复
热议问题