Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is strcpy in Java?

Tags:

java

What is strcpy in Java?

String s1, s2;

s1 = new String("hello");
s2 = s1; // This only copies s1 to s2.
like image 774
user1301568 Avatar asked Aug 29 '12 11:08

user1301568


People also ask

What is the use of strcpy?

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.

What is string copy in Java?

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.

What is the difference between strcpy and strncpy?

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 .

Where is strcpy defined?

The strcpy() function in C++ copies a character string from source to destination. It is defined in the cstring header file.


2 Answers

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";
like image 135
Peter Lawrey Avatar answered Oct 09 '22 18:10

Peter Lawrey


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.

like image 45
Jon Skeet Avatar answered Oct 09 '22 18:10

Jon Skeet