It’s a common misconception thinking (or worse teaching!) that, in Java, primitives are passed by value and objects by reference. Actually, everything in Java is passed by value as well as object references.
When a parameter is passed by value, an actual copy of it is really passed so that any change made will have only a local effect. For example:
1 2 3 4 5 6 7 8 9 10 11
As you can see the change made to the parameter passed to
increment, that is
a, affects only the local copy of it.
This proves that Java passes primitives by value.
Well, this is no surprise to anyone since you already knew that.
I’ll prove now, that also object references are passed by value, that is only a copy of the reference is passed.
Suppose you want to write a
swap method to swap two integers. Since you know you can’t use primitives you might
think to write the method using the wrapper class for int values, that is
Integer. Let’s try that:
1 2 3 4 5 6 7 8 9 10 11 12 13
This means that, even the object references are passed by value, as I stated at the beginning of this post!
What really happens is that, in case of references, a copy of the reference is passed and not the reference itself.
This means that, if the class is not immutable, you can change it’s state but you CANNOT change the actual memory address
the reference points to. Since
Integer is an immutable class you cannot change its state. So if you want to swap
int values, you need to write your own class that wraps an
int and provides a method to change the state of
this instance variable. In this case you can pass the copy of the references to a
swap method and call the method
that lets you change the state of the object. This is left as an exercise though. :-)