Grade 11 Computer Science · Basic types and their limits
Two families of type
Why the difference shows only when copying or comparing.
The same line, two opposite results
You copy a number to a new name and change the copy — the original does not move. You copy an array to a new name, in exactly the same way, and change the copy — the original changed too. There are not two rules here but one, and a single letter in the type’s name gives away in advance how it will behave.
In grade ten you drew names on one side and values on the other, with arrows between. In Java that picture gets an explicit law: there are types in which the name holds the value inside, and types in which the name holds an arrow to it. The difference is invisible when reading, and it settles everything when copying or comparing.
int a = 5;
int b = a; // b gets a copy of the value
b = 9;
System.out.println(a); // 5 — untouched
int[] xs = {1, 2};
int[] ys = xs; // ys gets a copy of the arrow, not the array
ys[0] = 9;
System.out.println(xs[0]); // 9 — the same arrayThe single rule behind both results
It is worth seeing that there are not two laws here but one: assignment always copies what the name holds. In a basic type the name holds the value, so a value is copied. In a reference type the name holds an arrow, so the arrow is copied — and both arrows point at the same place. This is exactly the explanation you saw in Python, only here half the types behave differently and so one must know which family each belongs to.
| The family | The name holds | Examples |
|---|---|---|
| Basic | The value | Whole, decimal, boolean, character |
| Reference | An arrow to the value | A string, an array, any class |
Example 1 — why the number did not change
- The name holds the value itself.
- The assignment copied the value.
- The two names are independent.
Example 2 — why the array did change
- The name holds an arrow.
- The assignment copied the arrow.
- Both point at the same array.