Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I copy Strings in Java?

Tags:

java

People also ask

How do you make a copy of a string?

Copying one string to another - strcpystrcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied.

How can I copy just a portion of a string?

We can use string function strncpy() to copy part strings. Part of the second string is added to the first string. strcpy(destination_string, source_string, n);

Which method can be used to copy part of a string to another variable?

If you want to copy part of string to another string, then valueOf and copyValueOf methods are useful.


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.


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";

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.