How can Java assignment be made to point to an object instead of making a copy?

When a variable is used as argument to a method, it’s content is always copied. (Java has only call-by-value.) What’s important to understand here, is that you can only refer to objects through references. So what actually happens when you pass a variable referring to an object, is that you pass the reference to the object (by value!).

Someone may tell you “primitives are passed by value” and “non primitives are passed by reference”, but that is merely because a variable can never contain an object to begin with, only a reference to an object. When this someone understands this, he will agree that even variables referring to objects are passed by value.

From Is Java “pass-by-reference” or “pass-by-value”?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

From http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

Java does manipulate objects by reference, and all object variables are references. However, Java doesn’t pass method arguments by reference; it passes them by value.

In Java, there is no counter part to the C++ “reference type” for primitives.

Leave a Comment