How should I copy Strings in Java?

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

    Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

    So you can copy as in your first example without any problem :

    String s = "hello";
    String backup_of_s = s;
    s = "bye";
    

提交回复
热议问题