Array Creation and Access
Why this matters
Imagine you're building a simple app to track your grades. You have one score from your first APUSH quiz, so you create a variable: int quizScore = 92;. Easy enough.
But then you take another quiz. And another. And a midterm. Suddenly you have quizScore1, quizScore2, quizScore3, midtermScore... it gets messy, fast. How would you calculate your average? You'd have to add them up one by one. What if you had 50 scores? This approach just doesn't scale.
This is where data collections come in. We need a way to group related data together in a single, organized structure. Today, we're going to learn about the most fundamental data collection in Java: the array. It’s the perfect tool for turning that messy pile of scores into a neat, manageable list.
Concept overview
flowchart TD
A[Start: Access array element] --> B{Is index >= 0?};
B -- No --> F[Error: ArrayIndexOutOfBoundsException];
B -- Yes --> C{Is index < array.length?};
C -- No --> F;
C -- Yes --> D[Access element at index];
D --> E[Return value / Assign new value];
E --> G[End];
F --> G;
Core explanation
Let's dive into how you can create and use these powerful tools in your own code.
What Is an Array?
At its heart, an array is a way to store a list of items. The two most important rules are:
- 1Same TypeEvery item in the array must be of the same data type. You can have an array of
ints, or an array ofStrings, but you can't have an array with anintnext to aString. - 2Fixed SizeOnce you create an array, its size cannot change. If you make an array to hold 10 numbers, it will always hold exactly 10 numbers.
Think of an array like an egg carton. An egg carton is designed to hold a specific number of eggs (its size is fixed), and you can only put eggs in it, not baseballs or car keys (all items are the same type).
Creating Your First Array
There are two main ways to create an array.
1. Using the new Keyword
This is the most common way. You declare the type, give it a name, and specify the size.
// Declaring and creating an array to hold 5 integers.
int[] dailySteps = new int[5];
Let's break this down:
int[]: This declares that we want an array of integers. The[]is what tells Java it's an array.dailySteps: This is the name of our array variable.new int[5]: This is the magic part. Thenewkeyword actually creates the array object in memory.[5]tells Java to allocate enough space for exactly 5 integers.
This is where a lot of students get confused: When you create an array this way, what's in it? Is it empty?
No, it's not empty. Java initializes each element to a default value based on the data type:
int:0double:0.0boolean:false- Object types (like
String):null
So, our dailySteps array right now looks like this conceptually: [0, 0, 0, 0, 0].
2. Using an Initializer List
Sometimes you know the exact values you want in your array from the start. For that, you can use an initializer list with curly braces {}.
// Create an array of doubles with specific values.
double[] prices = {12.99, 5.00, 23.50, 9.99};
// Create an array of Strings.
String[] friends = {"Maya", "Carlos", "Priya", "Liam"};
<figure class="lesson-figure"><div class="shr-widget" data-shr-widget="{"type":"array_animation","label":"prices","values":["12.99","5.00","23.50","9.99"],"highlight":[]}" aria-label="Two arrays. One named 'prices' with values 12.99, 5.00, 23.50, 9.99. Another named 'friends' with values 'Maya', 'Carlos', 'Priya', 'Liam'."></div><figcaption class="lesson-figure-caption">Arrays initialized with values using an initializer list. Java automatically determines the size.</figcaption></figure>
When you use an initializer list, Java automatically figures out the size of the array for you. The prices array has a length of 4, and the friends array also has a length of 4. You don't use the new keyword or specify the size in brackets.
Accessing and Modifying Array Elements
Okay, so you have an array. How do you get things in and out of it?
You use square brackets [] and an index.
Here's the single most important rule about indices in Java: They start at 0.
For an array of size N, the valid indices are 0, 1, 2, ..., N-1.
Let's use our friends array: {"Maya", "Carlos", "Priya", "Liam"}.
friends[0]is "Maya"friends[1]is "Carlos"friends[2]is "Priya"friends[3]is "Liam"
To get a value, you use the variable name and the index in brackets:
String bestFriend = friends[0]; // bestFriend is now "Maya"
System.out.println(friends[2]); // This will print "Priya"
To change a value, you do the same thing, but use it on the left side of an assignment statement:
// Let's say Priya moves away and Sofia moves in.
friends[2] = "Sofia";
// Now the array is: {"Maya", "Carlos", "Sofia", "Liam"}
The length Attribute
Remember how we said an array's size is fixed? You can always check that size using the array's length attribute. Notice it's just length — no parentheses! This is a common trip-up because the length() method for Strings does use parentheses.
int[] scores = {88, 92, 100, 74, 85};
System.out.println(scores.length); // Prints 5
String[] team = new String[11]; // A soccer team
System.out.println(team.length); // Prints 11
The length attribute is incredibly useful, especially when you want to loop through an array without hard-coding its size.
The Danger Zone: ArrayIndexOutOfBoundsException
What happens if you try to access an index that doesn't exist?
int[] scores = {88, 92, 100}; // length is 3. Valid indices are 0, 1, 2.
// Let's try to access the "third" element the way we speak in English.
int myScore = scores[3]; // DANGER!
Your program will crash and burn. Java will throw an ArrayIndexOutOfBoundsException. This is one of the most common errors you'll encounter when you start working with arrays.
See it in action
Worked examples
Let's walk through a couple of examples to make this concrete.
Calculating an Average Score
Problem: You've taken 4 exams in your history class. The scores are 94, 88, 79, and 97. Create an array to store these scores and then calculate and print the average.
Step-by-step Solution:
- 1Choose the right data type and creation methodThe scores are whole numbers, so
intis a good choice. Since we know the values upfront, an initializer list is the easiest way to create the array.int[] historyScores = {94, 88, 79, 97}; - 2Access the elements to sum them upTo find the average, we first need the sum. We can access each score using its index (0, 1, 2, and 3).
int sum = historyScores[0] + historyScores[1] + historyScores[2] + historyScores[3]; // sum = 94 + 88 + 79 + 97 // sum = 358Why this step? We need to aggregate the data in the array to perform a calculation. Accessing by index is the fundamental way to retrieve values.
- 3Calculate the averageThe average is the sum divided by the number of scores. We can get the number of scores using the
.lengthattribute.Here's a subtle trap:
sumis anintandhistoryScores.lengthis also anint. In Java, dividing anintby anintperforms integer division, which truncates any decimal part. To get a precise average, we should cast one of them to adouble.double average = (double) sum / historyScores.length; // average = (double) 358 / 4 // average = 358.0 / 4 // average = 89.5Why this step? This shows the interplay between array properties (
.length) and other Java rules (like type casting for accurate division). Many students would just writesum / historyScores.lengthand get89, which is incorrect.
-
Print the result.
System.out.println("The average score is: " + average); // Output: The average score is: 89.5
Tracking Weekend Chores
Problem: You have 5 chores for the weekend: "Mow lawn", "Do laundry", "Clean room", "Wash car", "Grocery shopping". Create an array to store these. Then, you finish cleaning your room and want to update its status to "Clean room - DONE".
Step-by-step Solution:
- 1Create the arrayThe chores are text, so we'll use a
Stringarray. An initializer list is perfect here.String[] chores = {"Mow lawn", "Do laundry", "Clean room", "Wash car", "Grocery shopping"}; - 2Identify the element to modify"Clean room" is the third item in our list. Since indices start at 0, this is at index
2. - 3Modify the elementWe use an assignment statement with the correct index to change the value.
chores[2] = "Clean room - DONE";Why this step? This demonstrates that arrays are mutable—their contents can be changed after creation. We're not changing the size of the array, just the value at a specific position.
- 4Verify the change (optional but good practice)Let's print the value at index 2 to see if it worked.
System.out.println("Status of third chore: " + chores[2]); // Output: Status of third chore: Clean room - DONE
Try it yourself
Ready to get your hands dirty? Give these a shot.
1. Daily Temperatures
You're tracking the high temperatures in Dallas for a week. The temperatures were 85, 88, 92, 90, 87, 84, 89 degrees Fahrenheit.
- Create an array named
dallasTempsto hold these values. - Print the temperature from the first day (Monday).
- On the last day (Sunday), the forecast was wrong. The actual temperature was 91. Update the array to reflect this change.
- Print the new temperature for the last day.
2. To-Do List Tracker
You want to track whether you've completed three key tasks: "Submit AP CSA homework", "Practice for the basketball game", and "Read Chapter 5".
- Create a
booleanarray to track the completion status of these three tasks. Initialize them all tofalseusing thenewkeyword. - Print the length of the array.
- Now, mark the first task as complete.
- Print the status of the first task to confirm it's
true.
Practice — 8 questions
In simple terms, arrays are like a numbered list of boxes where you can store a collection of items, but every item must be of the same type.
// Declaring and creating an array to hold 5 integers.
int[] dailySteps = new int[5];
- 4.3.A: Develop code used to represent collections of related data using one-dimensional (1D) array objects.
- 4.3.A.1
- An array stores multiple values of the same type. The values can be either primitive values or object references.
- 4.3.A.2
- The length of an array is established at the time of creation and cannot be changed. The length of an array can be accessed through the length attribute.
- 4.3.A.3
- When an array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
- 4.3.A.4
- Initializer lists can be used to create and initialize arrays.
- 4.3.A.5
- Square brackets [] are used to access and modify an element in a 1D array using an index.
- 4.3.A.6
- The valid index values for an array are 0 through one less than the length of the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException.
flowchart TD
A[Start: Access array element] --> B{Is index >= 0?};
B -- No --> F[Error: ArrayIndexOutOfBoundsException];
B -- Yes --> C{Is index < array.length?};
C -- No --> F;
C -- Yes --> D[Access element at index];
D --> E[Return value / Assign new value];
E --> G[End];
F --> G;
Read what Saavi narrates
Hello everyone, it's Saavi from Shrutam.
Imagine you're building an app to track your grades. You have one score, so you make a variable for it. Then you get another score, and another... soon you have a messy pile of variables. How would you find your average? It's a pain.
This is why we have arrays. An array is simply a container that holds a fixed number of values of a single type. Think of it like a set of numbered mailboxes, where each one holds a piece of data, and you can get to it using its number.
Let's walk through a quick example. Say you have four exam scores: 94, 88, 79, and 97. We can create an integer array to hold them, like this... we'd write `int[] historyScores = {94, 88, 79, 97};`
Now, how do we get the average? First, we need the sum. We can get each score by its index, and remember, indices start at zero! So we'd add the score at index 0, plus the score at index 1, plus 2, plus 3. That gives us a sum of 358.
Next, we divide the sum by the number of scores. We can get this number using the array's length attribute... so, `historyScores.length`, which is 4. Here's a pro tip: to get a decimal answer, we need to make sure we're not doing integer division. So we'd calculate 358.0 divided by 4, which gives us a beautiful, accurate average of 89.5.
Now, one of the most common mistakes I see is the "off-by-one" error. Let's say our array has a length of 4. That means the valid indices are 0, 1, 2, and 3. If you try to access the element at index 4... your program will crash with an `ArrayIndexOutOfBoundsException`. It's like trying to open mailbox number 4 when there are only mailboxes 0 through 3. Always remember, the last valid index is `length - 1`.
Arrays are a foundational concept. Once you master them, you've unlocked a huge part of what makes programming so powerful. Keep practicing, and you'll get it.
An array of length `N` has indices from `0` to `N-1`. The index `N` is always out of bounds.
Remember the last valid index is always `myArray.length - 1`. When looping, the condition should be `i < myArray.length`, not `i <= myArray.length`.
`length` is an attribute (a variable) of an array, so it has no parentheses. `length()` is a method (a function) of the `String` class, so it requires parentheses. Using `myArray.length()` will cause a compiler error.
For arrays, use `myArray.length`. For Strings, use `myString.length()`. Burn this distinction into your memory.
Arrays in Java have a fixed, immutable size. Once you `new int[10]`, it's a 10-element array forever.
If you need a dynamic, resizable list, you'll later learn about the `ArrayList` class. For now, if you need more space, you must create a new, larger array and copy the elements from the old one.
Parentheses are for calling methods, like `System.out.println()`. The syntax for array access is square brackets `[]`. `myArray(0)` is invalid syntax.
Always use square brackets for array indexing: `myArray[0]`.
When you create an array of objects, like `new String[5]`, it's filled with `null` values by default. Calling a method on a `null` reference, like `myStringArray[0].toUpperCase()`, will cause a `NullPointerException`.
After creating an array of objects, you must populate it with actual object instances, either with an initializer list or by assigning new objects to each index.
While `int scores[] = new int[5];` is technically valid Java syntax (for historical reasons), it's considered bad practice. The `[]` indicates the *type* is an array of integers, so it belongs with the type.
Always put the square brackets with the type to make your code clearer: `int[] scores = new int[5];`. This clearly says "`scores` is a variable of type `int[]`".