F
fxtrad
Hi Folks,
in the following example:
public class Test
{
static void operate (StringBuffer x, StringBuffer y)
{
x.append(y);
y = x;
}
public static void main (String [] args)
{
StringBuffer a = new StringBuffer ("A");
StringBuffer b = new StringBuffer ("B");
operate (a,b);
System.out.println(a + "," +b);
}
}
output is: AB,B
I thought arguments in java are always passed "by value". Meaning that
copies of objects "a" and "b" would be passed to the method "operate".
But in the above example, while object "b" is behaving as expected
(since it didn't change after being passed to "operate"), object "a"
have changed - which is confusing me. it's as if "a" was passed by
reference, while "b" was passed by value. Am I missing something here?
Thanks for your feedback.
in the following example:
public class Test
{
static void operate (StringBuffer x, StringBuffer y)
{
x.append(y);
y = x;
}
public static void main (String [] args)
{
StringBuffer a = new StringBuffer ("A");
StringBuffer b = new StringBuffer ("B");
operate (a,b);
System.out.println(a + "," +b);
}
}
output is: AB,B
I thought arguments in java are always passed "by value". Meaning that
copies of objects "a" and "b" would be passed to the method "operate".
But in the above example, while object "b" is behaving as expected
(since it didn't change after being passed to "operate"), object "a"
have changed - which is confusing me. it's as if "a" was passed by
reference, while "b" was passed by value. Am I missing something here?
Thanks for your feedback.