AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/4/4-3)
Unit 4 · Topic 4.3
4.3 Array Creation and Access
An array stores a fixed number of values of the same type under one name. This topic covers creating arrays, their default values, initializer lists, getting and changing elements by index, and the exception you get for a bad index.
Key terms
- array
- element
- index
length- initializer list
ArrayIndexOutOfBoundsException
What an array is
An array holds several values, called elements, all of the same type. The type can be a primitive, like int[], or a reference type, like String[]. The number of elements is set when the array is created and can never change. You get it from the length attribute: scores.length, with no parentheses (unlike a string's length() method).
An array is an object, so an array variable holds a reference. Assigning one array variable to another, like int[] b = a;, makes them aliases of the same array. Changing b[0] changes a[0] too.
The same thing happens when you pass an array to a method. The parameter gets a copy of the reference (3.6), so a method that changes arr[i] changes the caller's array. That's how a method can fill in or rearrange an array without returning anything.
Creating arrays
There are two ways to create an array.
- With
newand a size:int[] scores = new int[4];makes 4 elements, each set to the default value for the type:0forint,0.0fordouble,falseforbooleanandnullfor any reference type. - With an initializer list:
double[] prices = {2.5, 4.0, 1.25};makes an array of length 3 holding exactly those values.
Indexes
Each element has an index, starting at 0. Use square brackets to read or change an element: scores[2] is the third element, and scores[2] = 85; changes it.
The valid indexes run from 0 to length - 1. The last element is always arr[arr.length - 1]. Using any other index, such as -1 or arr.length, compiles fine but throws an ArrayIndexOutOfBoundsException when it runs.
int[] nums = {4, 8, 15};
System.out.println(nums[nums.length - 1]);
System.out.println(nums[nums.length]);
This prints 15 and then crashes on the third line, because index 3 doesn't exist in an array of length 3. The compiler can't catch this, since the index is only known when the code runs.
Arrays of objects
In an array of objects, like String[], each element holds a reference. A new array of objects starts full of null, not empty objects. Calling a method on one of those null elements, like names[0].length(), throws a NullPointerException. Fill in the elements before you use them.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Creating and accessing
What does this code print?
int[] scores = new int[4]; scores[0] = 90; scores[2] = scores[0] - 5; double[] prices = {2.5, 4.0, 1.25}; String[] names = new String[2]; System.out.println(scores[1] + " " + scores[2] + " " + scores.length); System.out.println(prices[prices.length - 1] + " " + names[0]);Show the solutionHide the solution
- Step 1:
scoresis made withnew int[4], so it starts as 0, 0, 0, 0. - Step 2:
scores[0] = 90changes the first element.scores[2]becomes90 - 5, which is 85.scores[1]is still 0, andscores.lengthis 4. - Step 3:
priceshas length 3, soprices[prices.length - 1]isprices[2], 1.25. - Step 4:
namesis a newStringarray, so every element isnull.
Answer: Two lines:
0 85 4, then1.25 null. - Step 1:
- Example 2
Two names, one array
What does this code print?
int[] a = {1, 2, 3}; int[] b = a; b[0] = 99; System.out.println(a[0] + " " + b[0]);Show the solutionHide the solution
- Step 1:
int[] b = a;copies the reference, not the array.aandbrefer to the same array. - Step 2:
b[0] = 99changes that one shared array. - Step 3: So
a[0]andb[0]are both 99.
Answer: It prints
99 99. - Step 1:
Common mistakes
- Using
arr.lengthas an index. The last valid index isarr.length - 1. - Writing
arr.length()with parentheses. For arrays,lengthis an attribute; for strings,length()is a method. - Thinking
int[] b = a;copies the array. It copies the reference, so both names share one array. - Calling methods on elements of a new object array before filling them in. They start as
null.
On the exam
- Tracing questions on arrays often hinge on default values or on an index of
length. Write out the array with its indexes before you trace.
Connected topics
Videos
Check yourself
4 questions on 4.3 Array Creation and Access. Pick an answer to see if you got it, and why.
Consider the following code segment.double[] d = new double[4];
d[1] = 2.5;
System.out.println(d[0] + d[1] + " " + d.length);What is printed as a result of executing the code segment?
Consider the following code segment.int[] a = {3, 1, 4};
System.out.println(a[a.length]);What is printed as a result of executing the code segment?
Which of the following statements creates an array that can hold 5 String references, all initially null?
Consider the following code segment.int[] a = {1, 2, 3};
int[] b = a;
b[0] = 9;
System.out.println(a[0] + " " + b[0]);What is printed as a result of executing the code segment?
0 of 4 answered