Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

 String s = "hello";

    String backup_of_s = s;

    s = "bye";

At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).

But is it really safe to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :

    String s = "hello";

    String backup_of_s = new String(s);

    s = "bye";

In other words, what's the difference (if any) between these two snippets?

1 Answer

0 votes
by (46k points)

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.

Related questions

0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...