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.

A basic type holds the value; a reference type holds an arrow.
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 array

The 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 familyThe name holdsExamples
BasicThe valueWhole, decimal, boolean, character
ReferenceAn arrow to the valueA string, an array, any class

Example 1 — why the number did not change

  1. The name holds the value itself.
  2. The assignment copied the value.
  3. The two names are independent.

Example 2 — why the array did change

  1. The name holds an arrow.
  2. The assignment copied the arrow.
  3. Both point at the same array.
The assignment did the same thing in both cases. What differed was what the name held.