質問

I am new to java technology, and may be it is a simple problem but I am confused like anything. I know that there is no concept of call by reference in java. It only uses call by value i.e. passing copy to another method

Kindly check the output of below code

public class Test {

    public static void main(String[] args) {
        StringBuffer a = new StringBuffer ("A");  
        StringBuffer b = new StringBuffer ("B");
        System.out.println("Before Operate"+a + "," +b);
         operate (a,b);
        System.out.println(a + "," +b);
    }
     static void operate (StringBuffer x, StringBuffer y) {
     x.append(y);
     y = x.append("C");
     y.append("D");
    }
}

output of above code is :ABCD , B (Second Syso)

i am not sure why this is appending everything in a not in b. I googled a lot but it only create confusion.So it would be great help if some one elaborate it completely.

Thanks in advance

P.S:-If this is already been asked at this forum kindly provide me a link,as i was not able to find it.

役に立ちましたか?

解決

Yes, Java is always pass-by-value, but you need to be aware of what the value is. For objects, the value passed is the reference to the object, not the object itself. See Is Java "pass-by-reference" or "pass-by-value"? for a detailed explanation.


i am not sure why this is appending everything in a not in b.

Because this:

x.append(y);
y = x.append("C");
y.append("D");

is exactly the same as this:

x.append(y);
x.append("C");
x.append("D");

Since StringBuilder#append() returns this, so that assignment to y in

y = x.append("C");

overwrites the reference to the object which was passed in (b) with a reference to x (aka a).

他のヒント

when you do this:

 y = x.append("C");

that all happend is just make x and y have the same reference (for x). And all you did on y after that operation was just did on x. So,At last all of the three operation just happend on x ,just like Matt Ball said:

x.append(y);
x.append("C");
x.append("D");

and x should be "ABCD",y should not be change.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top