What is strcpy in Java?
String s1, s2;
s1 = new String("hello");
s2 = s1; // This only copies s1 to s2.
strcpy() — Copy Strings The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.
Sometime back I was asked how to copy a String in java. As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.
The strcpy function copies string str2 into array str1 and returns the value of str1 . On the other hand, strncpy copies the n characters of string str2 into array str1 and returns the value of str1 .
The strcpy() function in C++ copies a character string from source to destination. It is defined in the cstring header file.
String is immutable so you would never need to copy it. (Except in rare circumstances)
e.g.
s1 = new String("hello");
is basically the same as
s1 = "hello";
and
s2 = s1;
is basically the same as
s2 = "hello";
This statement:
s2 = s1;
copies the value of s1
into s2
. That value is just a reference, so now s1
and s2
refer to the same object. So if this were a mutable type (e.g. StringBuilder
, or ArrayList
) then you'd be right to be concerned.
However, String
is immutable. You can't modify the object to change its text data, so just copying the reference is sufficient. Changing the value of s2
to refer to a different string (or making it a null
reference) will not change the value of s1
:
String s1 = "hello";
String s2 = s1;
s1 = "Something else";
System.out.println(s2); // Prints hello
If you really want to create a new String
object, you can use the constructor you're already (needlessly) using for s1
:
s2 = new String(s1);
However, that's very rarely a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With