That's a very good question. In Java, *everything* is pass-by-value (or pass-by-copy). The misconception comes from not understanding exactly what is being passed.
In Java, if you pass a primitive to a method, you pass the value as opposed to the actual reference to the variable. If you pass an Object, you pass the value of the *reference* (as opposed to the actual reference). This is a very confusing point, and regularly confuses programming experts.
Consider this code:
Code:
public class test{
static public void main(String[] args){
int a = 99;
System.out.println(a);
foo(a);
System.out.println(a);
}
static public void foo(int a){
System.out.println(a);
a = 10;
System.out.println(a);
}
}
Now, the output would be:
I trust you understand why.
Now, let's look at this second example:
Code:
public class test{
static public void main(String[] args){
String a = "Hello";
System.out.println(a);
foo(a);
System.out.println(a);
}
static public void foo(String a){
System.out.println(a);
a = "World";
System.out.println(a);
}
}
The output would be:
This is how you expected it to work, yes?
What you did in your example was actually perform operations on the ArrayList. You will find you can modify an object passed to a method to your hearts content, but you cannot modify the reference, because you are only working on a *copy* of the reference, not the *actual* reference.
Consider it this way - I create object "foo". I then pass a copy of the memory reference to a method. That method now knows where "foo" is stored in memory. I can perform all sorts of operations on that object. But when I exit the method, "foo" still references that object. I cannot destroy or manipulate that reference. It retains the changes I made to the *Object*, but doesn't reflect any changes I made to the *reference*.
Go ahead, you'll find that you cannot make that ArrayList you manipulated equal a new ArrayList from within the method. If you set it equal to a new ArrayList, when you exit the method, you'll find that "list" still equals the old ArrayList.