Is “new String()” immutable as well?

后端 未结 15 2405
日久生厌
日久生厌 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:09

    Immutability is not a feature of new, it is a feature of the class String. It has no mutator methods, so it immutable.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 00:18

    1-String is immutable.See this:

    Is a Java string really immutable?

    So you can create it with many way.

    2-Short answer: Yes will be empty.

    0 讨论(0)
提交回复
热议问题