Java Arrays — Introduction to Arrays

3 minute read

Arrays are one of the most fundamental data structures in Java. An array is a fixed-size, ordered collection of elements of the same type, stored in contiguous memory. Whether you’re storing a list of student grades, a sequence of sensor readings, or a deck of playing cards, arrays are your go-to tool.

In this chapter, you’ll learn how to declare, create, initialize, and access arrays in Java — along with understanding what happens in memory when you create one.


What is an Array?

An array is a container that holds a fixed number of values of a single type. Think of it like a row of numbered mailboxes — each box holds one item, and you access it by its number (index).

// Declare and initialize an array of 5 integers
int[] scores = new int[5];

Key facts about Java arrays:

  • Arrays are zero-indexed — the first element is at index 0
  • Arrays have a fixed size — once created, you can’t change the length
  • All elements must be the same type
  • Arrays are objects in Java (stored on the heap)

Declaring an Array

There are two valid syntaxes for declaring an array in Java:

// Preferred style (type[] name)
int[] numbers;
String[] names;

// Also valid but less common (C-style)
int numbers[];
String names[];

Best Practice: Always use type[] name — it makes it clear that the type is “array of int” rather than “int variable.”

At this point, no array has been created yet — we’ve only declared a variable that can hold a reference to an array.


Creating an Array

Use the new keyword to create an array with a specific size:

int[] scores = new int[5]; // Creates an array of 5 integers

Each element is automatically initialized to the default value for its type:

Type Default Value
int, short, byte, long 0
float, double 0.0
boolean false
char '\u0000' (null character)
Object references (String, etc.) null

Initializing an Array with Values

You can declare and initialize an array in one step:

// Array literal (size is inferred from the values)
int[] primes = {2, 3, 5, 7, 11};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

Or assign values individually:

int[] scores = new int[3];
scores[0] = 95;
scores[1] = 87;
scores[2] = 92;

Accessing Array Elements

Use the index (position number, starting from 0) to read or write elements:

String[] fruits = {"Apple", "Banana", "Cherry"};

System.out.println(fruits[0]); // Apple
System.out.println(fruits[1]); // Banana
System.out.println(fruits[2]); // Cherry

Expected output:

Apple
Banana
Cherry

Array Length

Every array has a length property (not a method — no parentheses):

int[] nums = {10, 20, 30, 40, 50};
System.out.println("Length: " + nums.length); // Length: 5

The last valid index is always length - 1.


ArrayIndexOutOfBoundsException

If you try to access an index that doesn’t exist, Java throws an ArrayIndexOutOfBoundsException:

int[] arr = {1, 2, 3};
System.out.println(arr[3]); // 💥 ArrayIndexOutOfBoundsException

This is one of the most common Java errors for beginners. Always ensure your index is between 0 and arr.length - 1.


Iterating Over an Array

Using a for loop

int[] scores = {95, 87, 92, 78, 88};

for (int i = 0; i < scores.length; i++) {
    System.out.println("Score " + i + ": " + scores[i]);
}

Using enhanced for-each loop

for (int score : scores) {
    System.out.println("Score: " + score);
}

The for-each loop is cleaner when you don’t need the index.


Arrays of Objects

Arrays can hold any type — including objects:

String[] cities = {"London", "Tokyo", "Paris", "New York"};

for (String city : cities) {
    System.out.println(city + " has " + city.length() + " characters");
}

Memory Layout

When you create an array, Java allocates a contiguous block of memory on the heap:

Stack                  Heap
┌──────────┐          ┌───┬───┬───┬───┬───┐
│ scores ──┼────────▶ │ 95│ 87│ 92│ 78│ 88│
└──────────┘          └───┴───┴───┴───┴───┘
                        [0] [1] [2] [3] [4]

The variable scores on the stack holds a reference (pointer) to the actual array data on the heap.


Common Mistakes

Mistake Fix
Accessing arr[arr.length] Last index is arr.length - 1
Forgetting arrays are zero-indexed First element is arr[0]
Trying to resize an array Arrays are fixed-size; use ArrayList for dynamic sizing
Comparing arrays with == Use Arrays.equals(a, b) instead

Try It Yourself

  1. Create an array of 7 days of the week and print each day with its index
  2. Create an array of 10 random integers and find the maximum value
  3. Create a String[] of 5 city names and print them in reverse order

What’s Next?

In the next chapter, we’ll learn how to sort, search, copy, and compare arrays using Java’s built-in Arrays utility class.

Updated: