StringBuffer
Please help in knowing the memory allocation happening for the variables under use. And description of the output
class Test
{
public static void main(String args[])
{
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
operate(a,b);
System.out.println("a = " +a + "b= " + b);
}
static void operate(StringBuffer x,StringBuffer y)
{
x.append(y);
y=x;
}
}
Sundar, these are all SCJP questions you're posting!
Anyway, this is how it'll happen...
First SB ( StringBuffer ) a is created pointing to "A". I'll denote this by a->A. Keep in mind that a does not contain A. A is the object, a is a reference to it.
Then SB b is created with "B" ==> b->B.
Then you call operate().
In operate, SB x and SB y will start off by being references to the original objects i.e x->A and y->B
x.append(y) will cause the original object A to have the object B appended to it. Hence the object which was A will now be AB. So x will now be a reference to AB and so will a, in main().
Therefore, now, x->AB and y->AB.
Now, when you say y=x what you are actually doing is this; making the reference y, a reference to the object that x is already a reference to ( AB ).
Hence, now y->AB and x->AB.
Now, when you return from operate(), a->AB and b->B because the object B was not modified at all. And since, the object that b is a reference to is not modified hence, when you print, you get AB for a and B for b.
I hope you get the distinction between the objects and the references. Everywhere that I state A and B, I mean a StringBuffer object with contents as "A" and contents as "B". Simlarly, AB implies a StringBuffer object with contents "AB".
Remember, these are NOT primitives, they are references to objects. So they are more than their values. To make an analogy ( one that should NOT be made though! ), You can consider a and b as pointers; if you change the value of the pointer, it does not modify the object that the pointer was pointing to. That is what is being done here, you could say that the pointer y was being assigned the address of pointer x. But the object being pointed to by y was not modified into the object being pointed by x. Also, b is a pointer to the same object so it can access it. Once again, this analogy was only to make things absolutely clear. There are no pointers in Java, and you should stop thinking in those terms. There are only references and objects.
> run it in NetBeans 5.5
> output: a=AB b=B
> In the function operate() ,there is a "y=x;", so I
> think y is also a reference to string "AB" .
> Why finally b' value is B,but not AB?
> Who can tell me ?
They did.
When you call a method with Object references, and then change the references inside the method, they only change for the scope of the method.