One of the Java programming questions I like to ask in interviews is: “Is Java pass-by-value or pass-by-reference?”

A surprising amount of Java developers get this wrong, generally because the variables you mostly deal with in Java (other than primitives) are actually references to objects, rather than containing the objects themselves. Most developers blurt out something like: “Objects are passed by reference, and primitives are passed by value.”

This is of course completely incorrect. Java is very strictly pass-by-value, which you should easily be able to confirm if you’ve ever (unsuccessfully) tried to write a swap() method that swaps two variables that reference immutable objects, such as Strings. It just so happens that the values that are being passed are generally object references. Instead of the statement above, one might say: “Object references are passed by value.”

Scott Stanchfield has written a great explanation of why Java is pass-by-value. He also has some strong thoughts on the terminology “references” vs. “pointers”. He argues that it was a bad idea of SUN to use the word “references” in order to differentiate them from the pointers as you might find them in C or C++. While the syntax for dealing with Java’s references is much simpler than C’s pointers, references otherwise behave exactly like pointers. Maybe calling Java’s object variables pointers instead of references would eliminate some of the confusion with regards to pass-by-value vs. pass-by-reference…