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 a
gets copied; in the context of methodB
, a
is a different variable that has the same value as in methodA
. So when you change it in methodB
, a
in methodA
still 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.
Strings are constant; their values cannot be changed after they are created.
What you could do is
a = methodB();
and return "bbb"
in methodB
. There is no reason to pass a
in because you are not operating on it; I think you were only doing it to try to change a
in the context that calls methodB
, which you cannot do.
Finally, the relevant part of the JLS is 8.4.1, which says
When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.