Unit 4 · 18 min
4.3 Array Creation and Access
An array is a fixed row of numbered boxes: same type in every box, numbered from 0 to length - 1.
Summary, objectives and course and exam description (CED) codes
An array stores multiple values of the same type, either primitive values or object references, and its length is fixed when it is created. Arrays made with new are filled with default values (0, 0.0, false or null), and an initializer list creates and fills an array in one step. You read and change elements with square brackets and an index from 0 to length - 1; any other index throws an ArrayIndexOutOfBoundsException.
By the end of this session you can
- 4.3.A Develop code used to represent collections of related data using one-dimensional (1D) array objects.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. What an array is
An array stores multiple values of the same type 4.3.A.1. Instead of six separate variables for six scores, you use one array variable with six elements. The values can be primitive values (such as int, double or boolean) or object references (such as String objects) 4.3.A.1.
The type of an array is written with square brackets after the element type:
int[] goals; // an array of int values
double[] prices; // an array of double values
String[] players; // an array of String references
Declaring the variable does not create the array yet. An array is an object, so it is created with new or with an initializer list (sections 2 and 3). This page is about one-dimensional (1D) arrays: a single row of elements.
Watch out: every element must match the declared type.
int[] scores = {90, 85.5, 77};
Compiler error:
error: incompatible types: possible lossy conversion from double to int
2. Creating an array with new
When you create an array with the keyword new, you give its length, and every element is set to the default value for its type 4.3.A.3:
| Element type | Default value |
|---|---|
int |
0 |
double |
0.0 |
boolean |
false |
any reference type (String, a class) |
null |
int[] goals = new int[4];
double[] prices = new double[3];
boolean[] present = new boolean[2];
String[] players = new String[3];
System.out.println(goals[0] + " " + prices[0] + " " + present[0] + " " + players[0]);
System.out.println("goals has " + goals.length + " elements");
Output:
0 0.0 false null
goals has 4 elements
The length of an array is established when it is created and cannot be changed 4.3.A.2. You read it with the length attribute 4.3.A.2. Notice: no parentheses. length is an attribute of the array, not a method.
int[] goals = new int[4];
int n = goals.length();
Compiler error:
error: cannot find symbol
And because the length cannot change, you cannot assign to it:
int[] goals = new int[4];
goals.length = 10;
Compiler error:
error: cannot assign a value to final variable length
3. Initializer lists
An initializer list creates an array and fills it with the values you list, all in one step 4.3.A.4. The length is the number of values in the list.
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
int[] laps = {62, 58, 60};
System.out.println(days.length);
System.out.println(laps.length);
Output:
5
3
Here is how days looks in memory. The index row is what you use to reach each element.
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
days |
“Mon” | “Tue” | “Wed” | “Thu” | “Fri” |
4. Accessing and modifying elements
Square brackets [] with an index access an element, and the same brackets on the left of = modify it 4.3.A.5.
int[] scores = {7, 4, 9, 6};
System.out.println(scores[2]); // read index 2
scores[1] = 10; // change index 1
scores[3] = scores[3] + 2; // read index 3, add 2, store it back
scores[0]++; // works like any int variable
System.out.println(scores[0] + " " + scores[1] + " " + scores[2] + " " + scores[3]);
Output:
9
8 10 9 8
| index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| before | 7 | 4 | 9 | 6 |
| after | 8 | 10 | 9 | 8 |
The index can be any int expression, such as a variable or scores.length - 1:
int[] scores = {7, 4, 9, 6};
int i = 1;
System.out.println(scores[i + 1]);
System.out.println(scores[scores.length - 1]); // always the last element
Output:
9
6
5. Valid indexes and ArrayIndexOutOfBoundsException
The valid index values for an array are 0 through one less than the length of the array, inclusive 4.3.A.6. For an array of length 4, that means 0, 1, 2 and 3. Using any index outside that range results in an ArrayIndexOutOfBoundsException 4.3.A.6.
The code compiles, because the compiler does not check index values. The error happens at run time, and the program stops.
int[] scores = {7, 4, 9, 6};
System.out.println(scores[3]);
System.out.println(scores[4]);
System.out.println("done");
Output:
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
Real view: this is the first line the console shows. “done” is never printed, because the exception stops the program. A negative index such as scores[-1] causes the same exception.
Watch out: scores[scores.length] is always out of bounds. The last element is scores[scores.length - 1].
6. Arrays of object references
An array of a reference type stores references, not the objects themselves 4.3.A.1. After new, every element is null, so you must assign objects before calling methods on them.
String[] team = new String[3];
team[0] = "Ana";
team[2] = "Leo";
System.out.println(team[0].length());
System.out.println(team[1]);
System.out.println(team[1].length());
Output:
3
null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "team[1]" is null
| index | 0 | 1 | 2 |
|---|---|---|---|
team |
“Ana” | null | “Leo” |
Printing a null element is fine; it prints null. Calling a method on it, such as team[1].length(), throws a NullPointerException. (The exact wording after the colon depends on your Java version and settings; on the AP® exam you only need the exception name.)
Lock it in: memory hooks
- Valid indexesZero to length minus one: the length itself is always one step too far.
- lengthArrays have no brackets after length; Strings do: arr.length versus str.length().
- Default valuesZero, zero point zero, false, null: numbers start at zero, booleans start false, objects start with nothing.
Common misconceptions
"The last element of an array is at index length."
Not quite. Indexes start at 0, so the last valid index is length - 1. Using index length throws an ArrayIndexOutOfBoundsException.
"You get the size of an array with length(), like a String."
Not quite. For an array, length is an attribute with no parentheses: scores.length. For a String it is a method: name.length().
"A new array of String objects is full of empty strings."
Not quite. Every element of a new array of a reference type is null. There are no String objects in it until you assign them.
"You can make an array bigger later if you need more room."
Not quite. The length of an array is set when it is created and cannot be changed. You would have to create a new, longer array.
Exam traps
- arr[arr.length] is always out of bounds; the last element is arr[arr.length - 1].
- arr.length() does not compile for an array; length has no parentheses.
- new double[3] holds 0.0 values and new boolean[3] holds false values, not 0 or null.
- An out-of-bounds index compiles fine; the error only appears when the code runs.
2PracticeRecall it, then check yourself
In 30 seconds
- An array holds many values of one type: primitive values or object references.
- Its length is fixed at creation; read it with the length attribute.
- new fills the array with default values: 0 (int), 0.0 (double), false (boolean), null (reference types).
- An initializer list such as {3, 8, 1} creates and fills an array in one step.
- Square brackets and an index read or change one element; valid indexes are 0 to length - 1.
- Any other index throws an ArrayIndexOutOfBoundsException at run time.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: Array Creation and Access
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Default values in an array created with new four defaults CED 4.3.A.3
- Ways to create a 1D array two ways CED 4.3.A.4, 4.3.A.3
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Arraytap to flip
An object that stores a fixed number of values of the same type, either primitive values or object references, reached by an index.
Example and CED codes -
Elementtap to flip
One value stored in an array or an ArrayList, at a position given by its index.
Example and CED codes -
Indextap to flip
The position of a character in a String, counted from 0. Valid indices run from 0 to length() - 1.
Example and CED codes -
Array lengthtap to flip
The number of elements in an array, set when the array is created and read with the length attribute (no parentheses).
Example and CED codes -
ArrayIndexOutOfBoundsExceptiontap to flip
The run-time exception thrown when code uses an array index less than 0 or greater than or equal to the array's length.
Example and CED codes -
nulltap to flip
A special literal meaning a reference variable is not associated with any object.
Example and CED codes -
Primitive typetap to flip
A data type for numbers and Boolean values whose variables hold the value directly. In this course: int, double and boolean.
Example and CED codes -
Reference typetap to flip
A data type used to define objects, that is, anything that is not a primitive type. Every class defines a reference type.
Example and CED codes
Questions students ask
What is the default value of an array element in Java?
It depends on the element type: 0 for int, 0.0 for double, false for boolean and null for any reference type, such as String.
How do I find the length of an array in Java?
Use the length attribute with no parentheses, for example scores.length. The last valid index is scores.length - 1.
What causes an ArrayIndexOutOfBoundsException?
Using an index less than 0 or greater than or equal to the array's length. It compiles, then stops the program at run time when that line runs.
Can an array hold different types of values?
No. Every element must have the type given when the array was declared, such as int or String.