String intern() behaviour

前端 未结 4 903
借酒劲吻你
借酒劲吻你 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 11:53

      String seven = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
    

    The literal "Hello2" will cause an object in the string constant pool to be created. The new String will create a new String object on the heap, with a copy of the content of the object for the literal.

    You should never create String object like that, because it's unnecessary and inefficient. When you do System.out.println(seven == seven.intern()); it will print true.

    Now when you do System.out.println(eight == eight.intern()); the string is returned from the string pool as it is already present, hence it will print false.

提交回复
热议问题