Hi All,
I have started preps for
SCJP and have joined JavaRanch recently. I have a question on passing Strings arguments to methods as references.
This is a
test program that I coded myself to test the pass by reference for Strings -
Output that I got was :
Testing
String........
In main-before func call: My String
In method convertString : New String
In main-after func call : My String
Below notes are from
http://www.javacoffeebreak.com/articles/toptenerrors.html - Point no. 6 - Confusion over passing by value, and passing by reference
"When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value..........
When you pass a
Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type. So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.
On a side note, since String contains no methods to modify its contents, you might as well be passing by value."
Considering the above notes, the String argument to convertString(String) method should be pass by reference, and String variable re-assignment in //Line 1 should be reflected in the main method (considering that I have not used any String methods and have assigned a new value to the String). But after the convertString() is called, the output prints "My String" instead of "New String" in the main method in //Line 2, while I was expecting it to print "New String".
Can anyone please explain this?