How should I copy Strings in Java?

前端 未结 5 1967
遥遥无期
遥遥无期 2020-12-12 14:14
    String s = \"hello\";
    String backup_of_s = s;
    s = \"bye\";

At this point, the backup variable still contains the original value \"hello

5条回答
  •  暖寄归人
    2020-12-12 14:51

    Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

    With this in mind, the first version should be preferred.

提交回复
热议问题