Arrays and reference semantics
We’ve talked a little bit about how variables that refer to objects don’t actually hold the objects themselves but instead a reference to one. That hasn’t really meant a lot to us yet, though. With arrays, it starts to be very important to pay attention to that distinction. Why?
- When one variable of an object type is assigned to another, the object is NOT copied but instead, both variables refer to the same object
- Modifying the value of one variable affects ALL references
Look at the following code:
int[] grades = {10, 15, 20, 12, 10};
int[] a2 = grades;
a2[2] = 9;
System.out.println(Arrays.toString(grades)); // prints [10, 15, 9, 12, 10] !!
As you can see, a2 and grades are two variables of type int[] which refer to the same object. Modifying either actually modifies the same thing. Similarly, printing either prints the same thing.
This is in contrast to Java’s primitive types which use value semantics:
- When one variable is assigned to another, its value is copied
- Modifying the value of one variable does not affect the other
Why would objects use reference semantics rather than value semantics?
- Efficiency: copying large objects takes a long time
- Sharing: it’s often useful to share an object’s data between methods
We’ve actually been using reference semantics without really mentioning them. Have you noticed that when you pass a reference to a DrawingPanel into a method, you’re modifying that DrawingPanel in the method rather than a copy of it?




