Ian McGrath
Ian McGrath

Reputation: 1012

Explanation of Java output

Code

class Test {
    public static void main(String args[]) {
        StringBuffer a = new StringBuffer("A");
        StringBuffer b = new StringBuffer("B");
        modify(a, b);
        System.out.println(a + " " + b);
    }

    public static void modify(StringBuffer a, StringBuffer b) {
        a.append(b);
        a = b;
        System.out.println(a + " " + b);
    }
}

I understand the print statement in function modify and I also know StringBuffer class modifies String inplace therefore a.append(b) makes String refer to "AB".

My question is how can String a be changed to "AB" outside the function modify but statement a=b has no impact outside function modify. Basically, when is variable passed by value, when by reference?

Upvotes: 1

Views: 158

Answers (3)

Peter Wooster
Peter Wooster

Reputation: 6089

A variable that contains an object is actually a reference to the object. So if you assign it to another variable, both variables refer to the same object.

When you pass a variable to a function the value is passed.

In the case of an object the value that is passed is a reference.

So, you can assign b to a in modify, but the effect is to the local value of the reference b, they are both the same after that and refer to object b. When you append b to a you are modifying the object referred to by variable a.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86744

Here's a simple picture:

main                            modify

StringBuffer <------a           a
     ^                          |
     +--------------------------+

StringBuffer <------b           b
     ^                          |
     +--------------------------+

In main, both a and b are references that point to separate StringBuffer instances. When main calls modify, it passes copies of the references a and b (pass by value). modify can change the contents of the StringBuffer instances, but if it changes the values of a and b, it operates only on its own local copies and does not affect what main's a and b point to.

The basic answer is that everything is passed by value, but when passing objects it's the reference that is passed (by value), not the object itself.

Upvotes: 2

Swapnil
Swapnil

Reputation: 8318

Java always uses pass by value. In cases of references, it's the value of the reference. When you pass a reference, it's possible to change the object referred to by the reference, but the reference being assigned to some other object has no consequences.

So, in your case, the object referred to by a can be changed, but the reference cannot be assigned to some other object (it can be as such, but has no effect).

Upvotes: 2

Related Questions