Is “new String()” immutable as well?

后端 未结 15 2514
日久生厌
日久生厌 2020-12-12 23:43

I\'ve been studying Java String for a while. The following questions are based on the below posts

Java String is special
Immutability of String in java

15条回答
  •  心在旅途
    2020-12-13 00:14

    Strings created will always be immutable regardless of how they are created.

    Answers to your questions:

    1. The only difference is:
      When string is created like -- {String a = "Hello World!";} then only one object gets created.
      And when it is created like -- {String b = new String("Hello World!");} then two objects get created. The first one, because you have used 'new' keyword and the second one because of the String property.

    2. Yes, for sure. There will be an empty entry created in the pool.

提交回复
热议问题