Asked in
Java Programming
C Programming

How you copy one string to another in java?


User Avatar
Wiki User
January 26, 2010 11:55AM

You can have two String variables (note that String variables are object references) refer to the same String object like so:

String str1 = "Hello";

String str2 = str1;

Now the str1 and str2 are references for the same String object containing the word "Hello".

If you actually want a new String object with a copy of the contents of the original String, you use the String constructor that takes a String argument, like so:

String str3 = new String(str1);

Now str1 and str3 refer to SEPARATE String objects that happen to contain the same sequence of characters (the word "Hello").

Since Strings objects in Java are immutable, they can be shared without worrying about the contents used by one variable being upset by the use through another variable as might happen with char[] arrays in C or C++ so the first method is probably sufficient for most cases.