2

for this method

public void testMethod( String paramString)
{
 String copyString = paramString;
}

does copyString create a new copy in memory of paramString?

3 Answers 3

3

In your example, paramString is a variable of a reference type, String to be exact. paramString holds the value of a reference to a String object. When you do

String copyString = paramString;

you are copying the value of that reference and assigning that copy to a second variable, copyString. You aren't copying an object, you are copying the value of a reference.

Sign up to request clarification or add additional context in comments.

Comments

2

No, you provide a reference to the same object.

The most important part here is that Strings are immutable. Even though these two objects have a reference to the same object, they will not affect eachother once the reference has been assigned.

Since strings are immutable, changing the value of the string in one reference will simply create a new string and make the reference point to the new one. The old reference will remain untouched.

Comments

0

Just as the other answers state, you're making copyString point to paramString.

If you want to produce a copy of paramString you should perform this assignment:

String copyString = ((String)paramString.clone());

clone() is an Object's method, that means every object from any class will have it, and returns a new instance of an object with another reference, or simple, a copy. As it returns an object, you must do the proper casting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.