4.3 Array Creation and Access
💻AP Computer Science A Unit 4 Review
4.3 Array Creation and Access
💻 AP Computer Science A
4.1
Ethical and Social Implications
4.2
Introduction to Using Data Sets
4.3
Array Creation and Access
4.4
Traversing Arrays
4.5
Developing Algorithms Using Arrays
4.6
Using Text Files
4.7
Wrapper Classes: Integer and Double
4.8
ArrayList Methods
4.9
Traversing ArrayLists
4.10
Developing Algorithms Using ArrayLists
4.11
2D Arrays
4.12
Traversing 2D Arrays
4.13
Implementing 2D Array Algorithms
4.14
Searching
4.15
Sorting
4.16
Recursion
4.17
Recursive Searching and Sorting
A 1D array in Java holds multiple values of the same type under one variable name, and its length is fixed when you create it. You access and change elements with square brackets and an index, where valid indices run from 0 to length - 1. For AP Computer Science A, watch array bounds closely because one off-by-one error can throw an ArrayIndexOutOfBoundsException.
Arrays are the foundation for everything else in Unit 4, which carries the largest weight on the AP Computer Science A exam. Getting array creation and indexing right sets you up for traversals, array algorithms, 2D arrays, searching, and sorting.
On the multiple-choice section, you will trace array code to predict output or spot which line throws an exception. On free-response code writing, you will create arrays, fill them, and access elements correctly, so off-by-one mistakes can cost easy points. The two skills emphasized here are writing code that uses arrays and determining the result of code that uses arrays.
What to Know About Array Creation and Access
- An array stores multiple values of the same type, either primitive values or object references.
- The length is set when the array is created and cannot change; read it with the
lengthattribute (no parentheses). - Using
newinitializes every element to a default:0forint,0.0fordouble,falseforboolean, andnullfor reference types. - Initializer lists like
{1, 2, 3}create and fill an array in one step. - Valid indices are
0throughlength - 1; anything outside that range throws anArrayIndexOutOfBoundsException. - Use square brackets to both read (
arr[i]) and modify (arr[i] = value) an element.
Core Concepts
Declaring and Creating Arrays
Declaring an array tells Java the element type and that the variable is an array, marked by square brackets. Creating the array with new reserves space for a fixed number of elements.
</>Java// Declaration: the brackets can follow the type or the name int[] scores; // preferred style int scores[]; // also valid // Creation: new reserves space for 7 ints, all set to 0 scores = new int[7];
The length you pass to new is locked in. You cannot grow or shrink an array later; you would have to create a new one.
Default Values
When you create an array with new but do not assign values, every element starts at the default for its type.
| Element type | Default value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
reference type (like String) | null |
</>Javaint[] counts = new int[3]; // {0, 0, 0} double[] totals = new double[2]; // {0.0, 0.0} boolean[] flags = new boolean[2];// {false, false} String[] names = new String[2]; // {null, null}
Initializer Lists
When you already know the values, an initializer list creates and fills the array at the same time. The length is set by how many values you list.
</>Javaint[] primes = {2, 3, 5, 7, 11}; // length 5 String[] days = {"Mon", "Tue", "Wed"}; // length 3
Indexing and Access
Indexing starts at 0, so the first element is at index 0 and the last is at index length - 1. The same square bracket notation reads a value and writes a value.
</>Javaint[] nums = {10, 20, 30, 40}; int first = nums[0]; // reads 10 nums[2] = 99; // writes 99, array is now {10, 20, 99, 40} int last = nums[nums.length - 1]; // reads 40
The length Attribute
Every array has a length attribute that gives the number of elements. It is a field, not a method, so there are no parentheses.
</>Javaint[] data = new int[5]; System.out.println(data.length); // 5 System.out.println(data.length - 1); // 4, the highest valid index
length always equals the number of elements the array was created with, even if some elements still hold their default values.
Worked Examples
Example: Create, fill, and read
</>Javaint[] temps = new int[7]; // 7 zeros temps[0] = 72; temps[1] = 75; // indices 2 through 6 are still 0 System.out.println(temps[0]); // 72 System.out.println(temps[temps.length - 1]); // 0 (last element default)
Example: Initializer list with object references
</>JavaString[] subjects = {"Math", "Science", "English"}; System.out.println(subjects[1]); // Science subjects[1] = "Biology"; // modifies index 1 System.out.println(subjects[1]); // Biology System.out.println(subjects.length); // 3
Example: Spotting a bounds error
</>Javaint[] arr = {4, 8, 15, 16}; // valid indices 0..3 System.out.println(arr[4]); // ArrayIndexOutOfBoundsException
Index 4 does not exist because the highest valid index is length - 1, which is 3.
Array Creation and Access on the AP Computer Science A Exam
Code Tracing: When you see array code, write the array out with its indices labeled 0, 1, 2, and so on. Track each assignment as it happens. If a line uses an index, check whether it falls in the range 0 to length - 1 before assuming the code runs.
Code Writing: When you create an array with new, remember the elements start at default values, so you may need a loop to fill them. When you need the last element, use arr[arr.length - 1], not arr[arr.length].
Common Trap: The most frequent slip is a loop condition that uses <= with length, which tries to read arr[arr.length] and throws an exception. Use i < arr.length to stop exactly at the last valid index.
</>Java// Correct loop bound for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
Common Misconceptions
- Misconception:
lengthis a method.Actually:lengthis not a method. Writearr.length, notarr.length(). It also is not the last index; the last index islength - 1. - Misconception: An array's size can be changed after creation.Actually: An array's size is fixed at creation. You cannot add or remove slots later; you would create a new array.
- Misconception: A declared array is the same as a created one.Actually: A declared array is not the same as a created one.
int[] nums;only declares the variable. Until you assign it (for example withnew), you cannot use it as an array: a local variable gives a compile error, and a field defaults tonull, which causes aNullPointerExceptionwhen used. - Misconception: An array made with
newholds nothing.Actually: An array made withnewis not empty in the sense of holding nothing. Each slot holds a default value like0ornull, which is different from an unassigned array variable. - Misconception: Indices start at 1, not 0.Actually: Indices start at 0, not 1. The first element is
arr[0], and counting from 1 is a common cause of off-by-one errors. - Misconception: An
ArrayIndexOutOfBoundsExceptionhappens when the code compiles.Actually: AnArrayIndexOutOfBoundsExceptionhappens at run time, not when the code compiles. The compiler will not catch an out-of-range index for you.
Related AP Computer Science A Guides
Practice Questions for 4.3
1 of 10
Consider the following complete Java program.
</>Javapublic class ArrayBounds { public static void process(int[] arr) { int total = 0; for (int k = 0; k <= arr.length; k++) { total += arr[k]; } System.out.print(total); } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4}; process(numbers); } }
What is the result of executing the program?
A.
The value 10 is printed to the console
B.
The value 15 is printed to the console
C.
A NullPointerException is thrown instead
D.
An ArrayIndexOutOfBoundsException occurs
Vocabulary
The following words are mentioned explicitly in the AP® course framework for this topic.Term | Definition |
|---|---|
1D array | An array with a single row of elements, organized in a linear sequence and accessed using a single index. |
array | A data structure that stores a fixed-size collection of elements of the same type in contiguous memory locations, accessed by index. |
ArrayIndexOutOfBoundsException | An error that occurs when attempting to access an array element using an index value outside the valid range of 0 through length minus one. |
default values | The initial values automatically assigned to instance variables by the default constructor based on their data type (0 for int, 0.0 for double, false for boolean, null for reference types). |
index | A numeric position in a string, starting from 0 for the first character and going up to one less than the length of the string. |
initializer list | A syntax used to create and initialize an array with specific values at the time of creation. |
length attribute | A property of an array that indicates the number of elements it contains and cannot be changed after creation. |
object reference | A value that points to the memory location where an object is stored, allowing access to that object. |
primitive values | Basic data types in Java such as int, double, and boolean that store actual values directly. |
See Fiveable more often in Google
Mark Fiveable as a preferred source and Google is more likely to show you our guides in Top Stories, with a "preferred" badge in AI Mode and AI Overviews.