Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Array Creation and Access

Lesson ~10 min read 8 MCQs

In simple terms: 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.

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.

A conceptual array of quiz scores, showing how a single structure can hold multiple related values.

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;
This diagram shows a flowchart for accessing an element in an array. The process starts by checking if the index is greater than or equal to 0 and less than the array's length. If both conditions are true, the element is accessed; otherwise, an ArrayIndexOutOfBoundsException occurs.

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:

  1. 1
    Same Type
    Every item in the array must be of the same data type. You can have an array of ints, or an array of Strings, but you can't have an array with an int next to a String.
  2. 2
    Fixed Size
    Once 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. The new keyword 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: 0
  • double: 0.0
  • boolean: false
  • Object types (like String): null

So, our dailySteps array right now looks like this conceptually: [0, 0, 0, 0, 0].

Default values for an `int` array created with `new int[5]`. All elements are initialized to 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="{&quot;type&quot;:&quot;array_animation&quot;,&quot;label&quot;:&quot;prices&quot;,&quot;values&quot;:[&quot;12.99&quot;,&quot;5.00&quot;,&quot;23.50&quot;,&quot;9.99&quot;],&quot;highlight&quot;:[]}" aria-label="Two arrays. One named &#039;prices&#039; with values 12.99, 5.00, 23.50, 9.99. Another named &#039;friends&#039; with values &#039;Maya&#039;, &#039;Carlos&#039;, &#039;Priya&#039;, &#039;Liam&#039;."></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

Code

    
Memory
Variables
Step 0 / 0

Worked examples

Let's walk through a couple of examples to make this concrete.

Example 1

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:

  1. 1
    Choose the right data type and creation method
    The scores are whole numbers, so int is 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};
  2. 2
    Access the elements to sum them up
    To 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 = 358

    Why 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.

  3. 3
    Calculate the average
    The average is the sum divided by the number of scores. We can get the number of scores using the .length attribute.

    Here's a subtle trap: sum is an int and historyScores.length is also an int. In Java, dividing an int by an int performs integer division, which truncates any decimal part. To get a precise average, we should cast one of them to a double.

    double average = (double) sum / historyScores.length;
    // average = (double) 358 / 4
    // average = 358.0 / 4
    // average = 89.5

    Why this step? This shows the interplay between array properties (.length) and other Java rules (like type casting for accurate division). Many students would just write sum / historyScores.length and get 89, which is incorrect.

Avoiding integer division pitfalls when calculating averages with `int` types.
  1. Print the result.

    System.out.println("The average score is: " + average);
    // Output: The average score is: 89.5
Example 2

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:

  1. 1
    Create the array
    The chores are text, so we'll use a String array. An initializer list is perfect here.
    String[] chores = {"Mow lawn", "Do laundry", "Clean room", "Wash car", "Grocery shopping"};
  2. 2
    Identify the element to modify
    "Clean room" is the third item in our list. Since indices start at 0, this is at index 2.
  3. 3
    Modify the element
    We 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.

  4. 4
    Verify 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
Tracing the sum calculation for `historyScores` using a loop (more scalable than manual addition).

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 dallasTemps to 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 boolean array to track the completion status of these three tasks. Initialize them all to false using the new keyword.
  • 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.
Visualizing the `dallasTemps` array before and after updating the last day's temperature.