Mastering call by value
Java uses call by value when passing arguments to methods and returning results from methods. Concisely, this means that Java makes a copy of something. Effectively, when you are passing an argument to a method, a copy is made of that argument and when you are returning a result from a method, a copy is made of that result. Why do we care? Well, depending on what you are copying – a primitive or a reference has major implications. An example of a primitive type is int
and an example of a reference type is an array.
In a method, there is a clear difference between the effect of changes when the parameter is a primitive type versus when the parameter is a reference type. We will demonstrate this shortly with a code example but first, to appreciate the differences, we need to understand what is happening in memory.
Primitives versus references in memory
An array is an object, whereas a primitive is not. We will discuss objects in detail in Chapter...