What is strcpy in Java?

What is strcpy in Java?

String s1, s2; s1 = new String("hello"); s2 = s1; // This only copies s1 to s2. 
+7
source share
5 answers

This statement:

 s2 = s1; 

copies the value of s1 to s2 . This value is just a reference, so now s1 and s2 refer to the same object. Therefore, if it was a mutable type (e.g. StringBuilder or ArrayList ), then you will be right to be concerned.

However, String is immutable. You cannot change the object to change its text data, so just copy the link. Changing the s2 value to link to another line (or creating a null link) will not change the s1 value:

 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 that you already (unnecessarily) use for s1 :

 s2 = new String(s1); 

However, this is very rarely a good idea.

+13
source

The string is immutable, so you do not need to copy it. (Except in rare cases)

eg.

 s1 = new String("hello"); 

basically coincides with

 s1 = "hello"; 

and

 s2 = s1; 

basically coincides with

 s2 = "hello"; 
+4
source

No s2 will refer to the newly created string object along with s1 .

0
source
  String s1, s2; s1 = new String("hello"); s2 = s1; // This only copies s1 to s2. Am I right? s1="adsfsdaf"; System.out.println(s2); System.out.println(s1); 

you are right s1 and s2 print a line not the same line ... but at the same time for objects changes made in one object affect another ... there is a need for a clone for the object .. there is no problem with the line

0
source

String Constructor makes work really easy because string objects in java are immutable

 String st="hello"; String st1=new String(st); 

OUTPUT will be from st1 greetings

0
source

All Articles