Skip to content
Study Hall
Lesson 1 of 5Arrays
Unit 6 · Lesson 1 of 5

Declaring and Using Arrays

Why a single name for many values changes what a program can do — and the indexing rules that come with it.

6 min read11 practice questionsAsk AI about this →

Key things to remember

  1. 1int[] a = new int[n]; creates n slots filled with the default value; int[] a = {1, 2, 3}; creates and fills in one step.
  2. 2Indexes start at 0, so the valid range is 0 to and the last element is a[a.length - 1].
  3. 3Arrays use .length with no brackets; Strings use .length() with brackets.
  4. 4Defaults: 0 for whole numbers, 0.0 for decimals, false for boolean, null for String and other objects.
  5. 5An array's length is fixed at creation and can never change.
  6. 6Any index below 0 or at least equal to the length throws ArrayIndexOutOfBoundsException.

Everything you have written so far uses one variable per value. That works until you need to hold thirty marks, and then it collapses: thirty declarations, thirty input lines, thirty additions, and a rewrite the moment a thirty-first student appears. An array fixes this. It is a single block of memory that holds many values of the same type, reached by position rather than by name, so the same three lines of code work for three values or three thousand.

// Without an array - unusable past a handful of values
int mark1 = 88;
int mark2 = 92;
int mark3 = 75;
int total = mark1 + mark2 + mark3;

// With an array - the same idea, but it scales
int[] marks = {88, 92, 75};
int total2 = marks[0] + marks[1] + marks[2];
The second version can be driven by a loop. The first version can never be.

There are two ways to make an array, and you choose between them based on whether you already know the values. The square brackets in int[] are part of the type: int[] is read as "array of int", a different type from plain int, and everything inside must be that one type. Note that the short initializer form {1, 2, 3} is only legal on the declaration line — splitting it into int[] a; then a = {1, 2, 3}; is a compile error, and you would have to write a = new int[]{1, 2, 3}; instead.

// Form 1: you know the SIZE but not the values yet.
// Java allocates 10 slots and fills them with the default value 0.
int[] scores = new int[10];

// Form 2: you know the VALUES. Java counts them and sizes the array for you.
int[] scores2 = {88, 92, 75};        // length 3

// Other types work exactly the same way
double[] temps = new double[7];
String[] names = {"Aisha", "Ben", "Chloe"};
boolean[] present = new boolean[30];
An array is a fixed row of boxes, all of one type, numbered from 0.int[] scores = {90, 72, 85, 61, 78};scores.length is 5 — a field, no brackets900721852613784?5no box herescores[0] is 90scores[4] is 78scores.length is 5scores[5] crashesIndexes run 0 to length − 1, so the last index is always one less than the length.Arrays use .length with no brackets; Strings use .length() with brackets. They are different things.The size is fixed when the array is created — you cannot grow it later, only build a bigger one.
Fig 1One array: a name, a type, a fixed length, and numbered slots.

The position of an element is its index, and indexes begin at 0, not 1. So an array of length 5 has indexes 0, 1, 2, 3 and 4 — there is no index 5. This feels arbitrary until you know where it comes from: the index is really an offset from the start of the memory block. The first element sits zero slots along from the start, the second sits one slot along, and so on. Once you think of it as an offset, zero-based indexing is the only version that makes sense.

A list of length 6 has indexes 0 to 5. There is no element 6.12[0]7[1]9[2]23[3]4[4]16[5]?[6]marks[0] → 12 len(marks) → 6marks[5] → 16 marks[-1] → 16 (Python only)marks[6] → IndexError: list index out of range
Fig 2Six elements, indexes 0 through 5. The last index is always one less than the length.
public class ScoreDemo {
    public static void main(String[] args) {
        int[] scores = new int[5];
        scores[0] = 88;
        scores[1] = 92;
        scores[2] = 75;
        scores[3] = 61;
        scores[4] = 94;

        System.out.println("First:  " + scores[0]);
        System.out.println("Third:  " + scores[2]);
        System.out.println("Last:   " + scores[scores.length - 1]);
        System.out.println("How many: " + scores.length);
    }
}
Output: First: 88, Third: 75, Last: 94, How many: 5.
The last index is length minus one
Write arr[arr.length - 1] whenever you want the last element. This is not a trick, it is the safest habit in array code: it stays correct when the array changes size, and it is the phrase that stops you from ever writing arr[arr.length].

An array reports its size through .length with no parentheses, because length is a stored property of the array object. A String reports its size through .length() with parentheses, because that is a method call. Separately, new int[10] does not leave the slots full of garbage: Java guarantees every element starts at the zero value for its type, which is why you can safely add up a fresh int[] and get 0 rather than nonsense. The one that catches people is String[], whose default is null rather than the empty string — printing an unassigned element shows the word null, and calling a method on it throws a NullPointerException.

What you haveHow you get its sizeWhy
int[] arrarr.lengthA field stored on the array — no brackets
String ss.length()A method the String class provides — brackets required
arr.length()Compile errorAn array has no method called length
s.lengthCompile errorA String has no public field called length
Element typeDefault valueWhat prints
int, short, long00
double, float0.00.0
booleanfalsefalse
charthe null character \u0000an invisible blank
String and any objectnullnull
Every new array is zero-filled. The object case is null, which is not an empty string.

Once created, an array's length can never change. new int[10] reserves exactly ten slots for the life of that array; there is no .add() and no way to grow it. If you need an eleventh value you must create a larger array and copy everything across. That sounds like a flaw, and in exchange you get something valuable: because the size and the type are fixed, the computer knows the exact address of element i by arithmetic alone, so reading arr[5000] costs the same as reading arr[0].

Anew int[size]
  • Use when the values are not known yet
  • You must supply the size as a number or a variable
  • Every slot is filled with the type's default
  • int[] daily = new int[days]; where days was read from the user
BInitializer list
  • Use when the values are known as you write the code
  • Java counts the values and sets the length for you
  • Only legal on the declaration line
  • int[] sides = {3, 4, 5};
int[] arr = {10, 20, 30};   // length 3, valid indexes 0, 1, 2

System.out.println(arr[2]);  // 30 - fine, this is the last element
System.out.println(arr[3]);  // CRASH: Index 3 out of bounds for length 3
Java checks every index as the program runs, and the message names both the index you asked for and the length you had.
arr at index arr.length always throws
Because indexes run from 0 to length minus 1, the index equal to the length is always one past the end — for every array, of every size, always. So arr[arr.length] is not a value that is sometimes wrong; it is guaranteed to throw ArrayIndexOutOfBoundsException. The correct expression for the last element is arr[arr.length - 1].

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Declare an array to hold seven daily high temperatures as decimals, store Monday's as 21.5 and Sunday's as 18.0, then print how many days are stored and Sunday's value.
Example 2
For int[] a = {4, 8, 15, 16, 23, 42}; give the value of a[0], a[3], a.length, a[a.length - 1], and say what a[6] does.
Example 3
This loop is meant to print every element of data but crashes on its last pass. Find and fix the bug: for (int i = 0; i <= data.length; i++) { System.out.println(data[i]); }

Where marks get lost

  • Treating the first element as index 1. a[1] is the second element, so every value comes out shifted by one.
  • Writing a.length() for an array or s.length for a String — the presence or absence of brackets is not optional.
  • Looping with i <= a.length, which runs one pass too many and throws on the last one.
  • Expecting a String[] to start full of empty strings. It starts full of null, so calling a method on an unassigned element throws a NullPointerException.
  • Trying to grow an array by assigning past the end. The length is fixed; you must build a bigger array and copy.

Flashcards 10

What is the index of the first element of an array?
How do you create an array of 20 integers with no values yet?
How do you create an array already holding 3, 4 and 5?
Array size vs String size
+ 6 more

Practice

1
For int[] a = {5, 10, 15, 20};, what is the value of a[1]?
2
For int[] scores = new int[8];, what is the largest index you may use?
3
Which expression gives the number of elements in int[] data?
4
After int[] a = new int[4]; and a[2] = 7;, what does a[0] + a[2] evaluate to?
5
Name the exception thrown by int[] a = {1, 2, 3}; System.out.println(a[3]);
6
Why does arr[arr.length] throw for every array, no matter its size?
7
Which declaration is NOT valid Java?
8
Match each array type to the value its elements hold immediately after new.
new int[5]
new double[5]
new boolean[5]
new String[5]
9
How many elements does int[] grid = new int[12]; hold?
10
Order the steps to set up and read an array whose size the user chooses.
  1. 1Create the array with new int[size]
  2. 2Read an element back using an index less than size
  3. 3Assign a value to each index from 0 to size minus 1
  4. 4Read the required size from the user into an int variable
11
What is the main cost of an array's fixed size?

Spot a mistake on this page? Let us know