Possible Duplicate:
Java pass by reference issue
In my codes below, methodA will be called, which then delegates a call to methodB, in doing so, methodB assigns the input parameter with String literal “bbb”, however, back at methodA, the string literal was not there, which section of the JLS defines this behavior?
package sg.java.test2;
public class TestApple {
public static void main(String args[]){
methodA();
}
public static void methodA(){
String a = null;
methodB(a);
System.out.println(a);
}
public static void methodB(String a){
a = new String("bbb");
}
}
this is a pass by value vs pass by reference issue. Java is pass by value ONLY. When you call
methodB(a)the reference
agets copied; in the context ofmethodB,ais a different variable that has the same value as inmethodA. So when you change it inmethodB,ainmethodAstill points to the original String.Another issue that comes into play here is that Strings are immutable, so you can’t change the value of a String once it is set. From the docs.
What you could do is
a = methodB();and return
"bbb"inmethodB. There is no reason to passain because you are not operating on it; I think you were only doing it to try to changeain the context that callsmethodB, which you cannot do.Finally, the relevant part of the JLS is 8.4.1, which says