Java Reference
In-Depth Information
Is Java going haywire? Not really. . . Some sources might explain this behavior by telling you
that primitive types in Java are passed by value (as seen before), but all other types are passed
by reference, meaning that the argument variable will refer to the same location in memory as
the original variable, and thus, any changes you make in the argument variable will be reflected
in the original variable (as they both reference the same location). This explanation, however, is
wrong.
To see why, consider the following slight modification of this example:
class Test {
int[] array = new int[]{1,2,3};
static void increaseFirstInt(int[] anIntArray) {
anIntArray[0]++;
}
static void changeIntArray(int[] anIntArray) {
anIntArray = new int[] {100,200,300};
}
public static void main(String[] args) {
Test t = new Test();
System.out.println("First element in array is: "+t.array[0]);
Test.increaseFirstInt(t.array);
System.out.println("First element in array is now: "+t.array[0]);
Test.changeIntArray(t.array);
System.out.println("First element in array is now: "+t.array[0]);
}
}
The output is probably different than what you would expect:
First element in array is: 1
First element in array is now: 2
First element in array is now: 2
If Java indeed passes nonā€primitive types by reference, the changeIntArray would effectively put a
new integer array in the same memory address the old array was stored in, and the final line of code
would output 100 instead of 2 , but this is not what is happening here. The truth is that all argu-
ments in Java are passed by value. The key thing to understand as well, however, is that Java objects
are internally represented as a reference to a location in memory, and this reference is passed as a
value. That is, the memory address of objects is passed by value.
At first sight, it seems like this should make no difference, but it does in fact help to figure out what
is happening in this example. Step through the code line by line. First, you create a new variable,
called t , as such:
Test t = new Test();
Try not to think of this variable as containing all information and behavior stored in the Test
object (this helps you understand the difference between classes and objects, but is not the way
Java uses object variables), but just as a piece of paper holding an address in memory, as shown in
Figure 4-4.
Search WWH ::




Custom Search