Java Arrays

Naveen AnamaneniUpdated · 4 min read

A train coach has 72 berths. You wouldn't give each berth its own separate name like berthOne, berthTwo... You'd number them and refer to "berth 23". An array does the same for data: it stores many values of the same type under one name, and you reach each one by its index (position number).

Declare, Create, Use

Marks.java▶ Try it
public class Marks {
    public static void main(String[] args) {
        int[] marks = new int[4];
        marks[0] = 78;
        marks[1] = 92;
        marks[3] = 64;
        System.out.println("First: " + marks[0]);
        System.out.println("Third: " + marks[2]);
        System.out.println("Count: " + marks.length);
    }
}
Output
First: 78
Third: 0
Count: 4

How it works

  1. Line 3 declares marks as an array of int (int[]) and creates room for 4 values with new int[4].
  2. Lines 4 to 6 store values by index. Indexes start at 0, so the 4 slots are marks[0] to marks[3].
  3. marks[2] was never set, so it holds the default value for int: 0.
  4. marks.length is the number of slots: 4.

Try it yourself: set marks[2] = 86; and print the third mark again.

Three Ways to Create an Array

FormExampleUse when
Size onlyint[] seats = new int[72];You'll fill the values later
Values directlyint[] marks = {78, 92, 86, 64};You know the values now
new with valuesmarks = new int[]{78, 92};Assigning a fresh array to an existing variable

The {...} shortcut only works on the line where the variable is declared. int[] a; a = {1, 2}; doesn't compile; write a = new int[]{1, 2};.

You may also see int marks[] (C style). It works, but int[] marks keeps the type together and is the Java convention.

How an Array Lives in Memory

The variable holds a reference; the array lives on the heap

An array is an object. The variable marks holds a reference to it; the slots themselves live together on the heap. That's why:

  • Every slot has a default value (0, false, null...) as soon as the array is created.
  • The size is fixed once created. To "grow" an array you create a bigger one and copy (see "Copying and Cloning Arrays"), or use an ArrayList (covered with collections, later in the course).
  • Reading any slot by index is instant, however big the array is, because the slots sit side by side and Java can compute where slot i is.

Common Mistakes

Starting from 1. marks[1] is the second element. Off-by-one mistakes are the most common array bug.

Mixing types. An int[] holds only ints. To store different types together, you'll use objects (Level 2).

Expecting println(marks) to print the values. It prints something like [I@1b6d3586, the type and a code. Use Arrays.toString(marks) (see "Arrays Class").

Interview Corner

What is an array in Java?

A fixed-size object that holds elements of one type, stored next to each other and accessed by an index from 0 to length - 1. The array variable holds a reference to the array object on the heap.

Can you change the size of an array after creating it?

No. The length is fixed. Create a new, bigger array and copy the elements, or use a resizable collection such as ArrayList.

Practice

  1. Easy: Create an array of the seven days' temperatures in your city and print the first and last values.
  2. Harder: Create new double[5], print values[0], then create new String[3] and print names[0]. Explain each result.

Quick check: Arrays

4 questions
1What is the index of the first element of an array?
2What does new int[3] contain right after creation?
3Which line doesn't compile?
4Can an array grow after it's created?

Key Takeaways

Was this tutorial helpful?

Lesson 68 of 482