Concepts / Accessing Array Elements by Index

Accessing Array Elements by Index

An array can be initialized by listing its values, separated by commas, between a pair of braces, and its length is the number of items in that list.

  • Programming

One Name for Many Values

Suppose a program stores a list of names in an array. Sometimes the program needs the whole list, and sometimes it needs just one entry, such as the name in a particular position. How does a program point at one entry without copying the others? This article answers that question for arrays, and it does so by tracing exactly what happens to the array's contents as each statement runs.

An array is one name for one object that holds many values. The variable name, such as namelist, refers to the array as a whole. Individual values inside the array are reached through the same variable name combined with an index number written inside square brackets. Before we reach individual values, though, we need to know how an array gets its values in the first place. Keep one question in mind as you read: at which point in a program is the array being filled, and what does the statement that does the filling allow?

Filling an Array with a Braces List

An array holds several elements rather than a single value, so initializing an array variable means supplying those elements at once. One form lists the values, separated by commas, and encloses the whole list between a pair of braces. The list is attached to the declaration itself, so the array variable is created and filled in one statement.

java

Read this statement as a single action. It names the array, smallPrimes, sets its element type to int, and provides the values that will go into it. The length is not written anywhere in the statement. The source explains that this statement creates an array of int with length 10, filled with the values in the list. The length is determined by counting the items in the braces. If you add or remove a value inside the braces, the length changes with it.

Tracing smallPrimes Index by Index

Now let us trace the state of smallPrimes. Counting starts at zero, so the first value sits at index 0 and the last value sits at index length minus 1, which is index 9 here. The diagram shows the ten positions that result from the list, with the value of each position beneath it. Notice that the value 5 sits at index 2, because index 0 holds 2, index 1 holds 3, and index 2 holds 5.

index 02index 13index 25index 37index 411index 513index 617index 719index 823index 929
Which slot does index 2 refer to, and how do the indexes line up with the values from first to last?

The array has length 10 because the list has ten items, and the highlighted position shows that index 2 is the third slot, holding the value 5. The index is a position number, not the value itself. Reading smallPrimes[2] gives you 5, while the index is 2.

Why the Braces List Fails in Assignment

What do you think happens?

Given smallPrimes already exists, will this second line compile in Java?

  • Yes, it compiles and replaces the contents

  • No, the compiler rejects it

Reveal answer
Answer:

No, the compiler rejects it

The braces list is recognized only in a declaration. The values on the second line are reasonable on their own, so the problem is entirely the syntax's position in the statement.

java
Notes on the code
  • Line 1 is a declaration, so the braces list is allowed.
  • Line 2 is an assignment to an existing array variable, and the braces list is not allowed there. This line does not compile.

Creating an Array with new and Its Defaults

The source describes a second way to initialize an array variable: give it an array created with the new operator. Unlike the braces form, this approach can also be used in assignment statements. You specify the element type and the size, and Java creates an array of that size.

java
Notes on the code
  • The new operator sets the element type and the size.
  • The second line is legal because the new form can appear in an assignment, unlike the braces list.

When an array is created this way, all of its elements have their default value. The source does not list those defaults in this passage, but in Java the default for an int element is 0 and the default for a String element is null. So a freshly created nameList holds 100 null references until you store strings into it. Nothing has been assigned yet, but every slot already has a defined default.

Key point

The new operator gives every element its default value, so an array created with new is usable immediately, though its slots hold defaults rather than the values you intend until you assign them.

Choosing Between the Two Forms

Both forms create arrays, but they differ in when the values are known and where the statement can appear. Use the table as a decision aid.

QuestionBraces listnew operator
When are the values known?At declaration timeCan be filled later
Where can the statement appear?Only in a declarationIn a declaration or an assignment
What do elements contain at creation?The values you listedEach element's default value
Typical useFixed known values, such as smallPrimesA set size, filled afterward, such as nameList
Can it replace an existing array's contents?NoYes, by assignment

Choosing the initialization form

In short: if you already know the values and the array is being declared, the braces list states them directly. If you need an array of a particular size and plan to fill it afterward, or you need to replace an array's contents later in the program, the new operator is the form the source allows in assignment.

Reaching One Element with an Index

The syntax for an element has two parts: the array name, followed by the index in square brackets. In the form array_name[index], the array name identifies which array you mean, and the index identifies which element of that array you mean. The source's example is namelist[7], which refers to the element at index 7 in the array named namelist. Notice that namelist by itself still refers to the array as a whole, while namelist[7] refers to just one piece of it.

namelistnames the whole array[7]selects index 7namelist[7]one element, used like avariablearrayindex
In an expression like namelist[7], which part names the array, which part selects the slot, and what is the result?

The diagram below in the anatomy shows the array name pointing at the whole collection, and the reference namelist[7] pointing at one position inside it. The neighboring positions, index 6 and index 8, are only context; their contents are not part of the reference. The diagram is a picture of the idea, not a claim about how the language stores arrays internally.

Using an Element Like an Ordinary Variable

Once you have written an element reference, you can treat it as an ordinary variable. You can assign a value to it, print it, or use it in an expression. Reading an element and writing an element use the same notation. The element is not a special kind of thing in these operations; it simply has the array name and index as its name.

Code walkthrough
String[] nameList = new String[100];
nameList[7] = "Ana";
System.out.println(nameList[7]);
int total = smallPrimes[2] + smallPrimes[3];
System.out.println(total);
  1. 1
    Line 1 creates nameList with 100 slots, each holding the default null.
  2. 2
    Line 2 stores the string Ana in index 7, so only that slot changes.
  3. 3
    Line 3 prints the value at index 7, which is Ana.
  4. 4
    Line 4 reads index 2 (value 5) and index 3 (value 7), adds them, and stores 12 in total.
  5. 5
    Line 5 prints 12.
  • nameList[7] appears on the left of an assignment, so it receives a value.
  • nameList[7] appears inside println, so its current value is printed.
  • smallPrimes[2] and smallPrimes[3] appear in an expression, giving 5 + 7.
Output
Ana
12

Reading Length and Why It Is Read-Only

An array also carries a value that describes its size. You refer to it by writing the array name, then a period, then the word length. For the array named smallPrimes, the length is written smallPrimes.length, and it reads as 10. The length is determined by the number of items the array holds, and it describes the array rather than one of its contents.

java
Output
10
Notes on the code
  • Reading smallPrimes.length is allowed and prints 10.
  • Assigning to smallPrimes.length is rejected, because the length cannot be changed.

Common Mistakes with Indexes and Length

  • Common mistake

    Using the braces list in an assignment to refill an existing array

    What it looks like
    smallPrimes = {31, 37, 41};
    Why it fails

    The braces form is recognized only in a declaration, so the compiler rejects it here.

    Do this instead

    Use the new operator in the assignment, for example smallPrimes = new int[]{31, 37, 41};, or assign individual elements.

  • Common mistake

    Treating the index as the value stored in the slot

    What it looks like

    Reading smallPrimes[2] and expecting 2

    Why it fails

    Counting starts at zero, and index 2 is the third slot, which holds 5.

    Do this instead

    Read the value at the index. smallPrimes[2] gives 5.

  • Common mistake

    Assuming new leaves elements empty or unusable

    Why it fails

    Every element gets its default value, such as 0 for int or null for String.

    Do this instead

    Expect defaults, then assign real values before relying on them.

  • Common mistake

    Trying to set the length of an array

    What it looks like
    smallPrimes.length = 5;
    Why it fails

    The length describes the array and cannot be assigned a new value.

    Do this instead

    Create a new array of the size you need, or read the length with smallPrimes.length.

Practice: Predict the Element

MEDIUM

Given int[] smallPrimes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; and then the statement System.out.println(smallPrimes[7] + smallPrimes.length); what is printed? Work out which slot index 7 refers to, read its value, and add the length.

Hints
  • Count from index 0: 2 is index 0, so which value is index 7?
  • The length is 10, which is the number of items in the braces.
  • Index 7 holds 19, so the answer is 19 plus 10.

Key Takeaways

  • An array can be initialized with a braces list of values, but that form works only in a declaration statement, not in an assignment.
  • The new operator creates an array of a given type and size, can be used in assignment, and gives every element its default value.
  • Use the braces list when values are known at declaration time, and the new operator when the array must be created with a size and filled later.
  • The array name refers to the whole array, while array_name[index] refers to one element, and that element can be assigned, printed, and used in expressions like an ordinary variable.
  • The length is read with array_name.length, describes the array rather than an element, and cannot be assigned.