What is strcpy in Java?
String s1, s2;
s1 = new String("hello");
s2 = s1; // This only copies s1 to s2.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This statement:
copies the value of
s1intos2. That value is just a reference, so nows1ands2refer to the same object. So if this were a mutable type (e.g.StringBuilder, orArrayList) then you’d be right to be concerned.However,
Stringis immutable. You can’t modify the object to change its text data, so just copying the reference is sufficient. Changing the value ofs2to refer to a different string (or making it anullreference) will not change the value ofs1:If you really want to create a new
Stringobject, you can use the constructor you’re already (needlessly) using fors1:However, that’s very rarely a good idea.