Question

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");
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

Java is pass by value, not pass by reference.

The method signature is shorthand for this:

methodB() {
    String a = arguments[0];

i.e. it is a difference reference. When you assign to 'a', you are assigning to the reference 'a' created as part of the method signature, not to the 'a' you declared in the code block that contained the call to methodB().

You can modify the value if it is an object, however.

class MyObj {
    String prop;
    public MyObj(String s) { prop = s; }
    public MyObj() { }
}

public void methodB(MyObj o) {
    o.prop = "foo";
}

public void methodA() {
    MyObj a = new MyObj();
    System.out.println(a.prop); // null
    methodB(a);
    System.out.println(a.prop); // foo
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top