I keep seeing this when researching Java arguments on the site but I believe I am misunderstanding it.
Question 1: Is Java "pass-by-reference" or "pass-by-value"?
Question 2: Does Java pass by reference?
People keep saying that in java reference types are passed by value, so that the reference itself isn't changed. And I believe my confusion comes from what the "references itself" is.
Originally I interpreted it to mean that what the argument was referring to, couldn't be changed or modified in any way, such as something being added to a list. Sadly this to some degree is wrong and has caused interesting results.
When I run the simple code below I get [test1, test2], so in my mind "the reference" list got changed.
import java.util.ArrayList; import java.util.List; public class HelloWorld { public static void main(String[] args) { List list = new ArrayList(); list.add("test1"); breakStuff(list); System.out.println(list.toString()); } public static void breakStuff( List l ) { l.add("test2"); } } With my current "idea" of what the people mean (answers to Question 1), they are wrong as things are changing. What am I not understanding or overlooking?
Are the people referring to the fact that you can modify the data the argument is referencing, but you can't change which "data/object" the argument is referring to?
ArrayListis mutable), but you cannot make the variable in the caller refer to a differentList. The acid test for pass-by-reference is whether you can write aswap(Object a, Object b)method that will switchaandbaround in the caller. By the way, you shouldn't use raw typesListandArrayList, but insteadList<String>andArrayList<String>.