Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

CONFUSED: If I pass a String as a parameter, is it passed as a reference?

807601May 5 2008 — edited May 8 2008
I'm reviewing for my AP Computer Science A exam tomorrow, which happens to be in Java!

I came across this question:

Assume the following declarations have been made:
private String s;
private int n;

public void changer(String x, int y)
{
x = x + "peace";
y = y * 2;
}
Assume s has the value "world" and n is 6. What are the values of s and n after the call changer(s, n)?

The correct answer is, apparently, s = "world" and n = 6, as it was when it started. I know that this is true for the integer, since it is passed by a value and a local copy is made in the method. However, what about String? I was under the impression that the reference to the s String would be sent to the changer method, and any change that was made to that String inside the method would be made to that instance of the String in memory, thus acting across the board. Does it have to do with a new memory slot being allocated for the newly concatenated String?

Thank you SO much in advance for your help! I need to make this distinction for tomorrow!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 5 2008
Added on May 5 2008
13 comments
372 views