Ok, I know that String objects are immutable, so if I need to "copy" the string content from a given string A to another one B I can assign the reference to A like (method 1):
String B = A;
instead of (method 2)
String B = new String(A);
because since there's no way to modify A I'm sure that by referring to B I obtain the same character sequence. Right?
But what happens in this situation described below?
I have a class C that has a String field "subject" and a constructor that take as argument a String "arg" and it must initialize subject to a character sequence equal to the one of "arg".
I have the following code:
public C getSomeC(...){
// some code to set the String A that is defined inside this function
return new C(A);
}
This way I simply call getSomeC(.) from some other point in my program so as to get my C instance.
But what changes whether I use method 1 or 2 in the constructor of C to define C.subject?
If I use the method 1 I pass to C constructor by value the reference of A and I assign to subject the reference to A right? But A has a visibility limited to method getSomeC(..) While I want my C instance to be used outside that method. What happens inside java in this case? Does the reference A be destroyed at the end of getSomeC(.) while the object remains alive because referred by instanceofC.subject?
What if I use method 2 instead?