Chapter 6 Arrays
So far the data types we’ve focused on have been the three primitive data types
int
, double
, and boolean
. We’ve made a little bit of use of String
for generating output and mentioned that it is not a primitive type but rather a reference type.
In this unit we are going to look at arrays which as our first real dive into a reference type. Arrays sit a bit between the primitive types and classes, which we’ll learn about in Chapter 8 Classes, but they give us a good way to start to understand the difference between primitive and reference types. So we’ll start with a quick overview here before getting into arrays themselves in the next section.
One way to describe the distinction is that primitive types are the things the computer actually knows about and reference types are defined by Java.
For example, modern CPUs know how to do arithmetic with thirty-two-bit integers, i.e.
int
values, and sixty-four-bit floating point numbers, i.e. doubles
. That is, completely independent of Java or any other programming language, they have circuitry devoted to interpreting sets of thirty-two or sixty-four bits in a certain way so we can do math with them. Similarly, the CPU has circuitry for doing Boolean logic that map very directly to what we can do in Java with boolean
values. But anything beyond the handful of primitive types the computer inherently understands are represented in Java by reference types.
Typically reference types represent more data than can fit in thirty-two or sixty-four bits; many can require an arbitrary amount of memory. For instance, a
String
can be short like "foo"
but it can also be millions characters long, such as the complete text of War and Peace. Arrays, likewise, can represent essentially arbitrary amount of data from a handful of values to millions or even billions.
To represent arbitrarily large values Java splits the value into two parts which together make up an object. The actual data—the text of War and Peace in a
String
or the millions of numbers in an array—is called the object data and it lives somewhere in the computer’s memory. But to get at the object data we need a special number, called a reference, that the CPU knows how to deal with. A reference is a single value that tells the CPU where in memory the object data lives. References, not the object data they refer to, are assigned to variables and passed as arguments to methods when dealing with objects.
Most of the time we don’t have to distinguish between the object data and the reference to it since in Java there’s no way to get at the object data except through the reference. But when we say the value of some variable is a particular object what we really mean is that the variable holds a reference to that object’s data. And when we say an object contains a particular value, we means that that value is somewhere in the object data.
With that preamble out of the way, we’re ready to actually look at arrays and how to use them.