How should I copy Strings in Java?

前端 未结 5 1956
遥遥无期
遥遥无期 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:38

    Your second version is less efficient because it creates an extra string object when there is simply no need to do so.

    Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.

提交回复
热议问题