Java String Copy Examples

Strings are immutable in Java, which means that a String object cannot be modified after its construction. Hence, 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 given below.
String str = "hello"; String newStr = str; str = "bye";

String s = "hello";

creates a new String instance and assigns its address to s (s being a reference to the instance/object)

String newStr = str;

creates a new variable newStr and initializes it so that it references the object currently referenced by str.

Note1: String immutability guarantees that this object will not be modified: our backup is safe.

Note 2: Java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable (newStr in this case)

Finally, str = "bye"; creates another String instance (because of immutability, it's the only way), and modifies the str variable so that it now references the new object.

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.

Here we have full examples

public class JavaStringCopy1 { public static void main(String args[]) { String str = "hello"; String strCopy = str; str = "world"; System.out.println(strCopy); // prints "hello" } }

Alternate ways to copy the String in Java

We different ways to copy the String to another String in vava.We cn use the assignment operator as given below.

Using String.valueOf() method

String str = "Hello World"; String strCopy1 = String.valueOf(str); String strCopy2 = String.valueOf(str.toCharArray(), 0, str.length());

Using String.copyValueOf() method

String str = "Hello World"; String strCopy1 = String.copyValueOf(str.toCharArray()); String strCopy2 = String.copyValueOf(str.toCharArray(), 0, str.length());

In this article, we have seen the Java String Copy Examples.