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.
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.
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.
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?
Reveal 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.
- 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.
- 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.
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.
| Question | Braces list | new operator |
|---|---|---|
| When are the values known? | At declaration time | Can be filled later |
| Where can the statement appear? | Only in a declaration | In a declaration or an assignment |
| What do elements contain at creation? | The values you listed | Each element's default value |
| Typical use | Fixed known values, such as smallPrimes | A set size, filled afterward, such as nameList |
| Can it replace an existing array's contents? | No | Yes, 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.
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.
String[] nameList = new String[100];
nameList[7] = "Ana";
System.out.println(nameList[7]);
int total = smallPrimes[2] + smallPrimes[3];
System.out.println(total);- 1Line 1 creates
nameListwith 100 slots, each holding the default null. - 2Line 2 stores the string Ana in index 7, so only that slot changes.
- 3Line 3 prints the value at index 7, which is Ana.
- 4Line 4 reads index 2 (value 5) and index 3 (value 7), adds them, and stores 12 in total.
- 5Line 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] andsmallPrimes[3] appear in an expression, giving 5 + 7.
Ana
12Reading 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.
10- Reading
smallPrimes.lengthis allowed and prints 10. - Assigning to
smallPrimes.lengthis 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 likesmallPrimes = {31, 37, 41};Why it failsThe braces form is recognized only in a declaration, so the compiler rejects it here.
Do this insteadUse 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 likeReading smallPrimes[2] and expecting 2
Why it failsCounting starts at zero, and index 2 is the third slot, which holds 5.
Do this insteadRead the value at the index. smallPrimes[2] gives 5.
Common mistake Assuming new leaves elements empty or unusable
Why it failsEvery element gets its default value, such as 0 for int or null for String.
Do this insteadExpect defaults, then assign real values before relying on them.
Common mistake Trying to set the length of an array
What it looks likesmallPrimes.length = 5;Why it failsThe length describes the array and cannot be assigned a new value.
Do this insteadCreate a new array of the size you need, or read the length with smallPrimes.length.
Practice: Predict the Element
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.