Array Basics

What is an Array?

An array stores a fixed number of values of the same type in one variable. Each value (element) has an index starting at 0.

int[] marks = {78, 92, 65, 88};

 index:   0    1    2    3
        +----+----+----+----+
        | 78 | 92 | 65 | 88 |      marks.length = 4
        +----+----+----+----+

Creating Arrays

Example

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88};          // with values
        String[] names = new String[3];          // empty, size 3
        double[] prices = new double[2];

        names[0] = "Arjun";
        names[1] = "Bhavna";
        prices[0] = 49.5;

        System.out.println(marks[1]);
        System.out.println(marks.length);
        marks[2] = 70;                            // change an element
        System.out.println(marks[2]);
        System.out.println(names[0] + ", " + names[2]);   // unset String -> null
        System.out.println(prices[1]);                    // unset double -> 0.0
    }
}

Output

92
4
70
Arjun, null
0.0
Element typeDefault value
int, long, byte, short0
double, float0.0
booleanfalse
char'\u0000'
objects (String...)null

Index Out of Bounds

Example

An array has a fixed size. Using an index outside 0 to length - 1 throws an exception.

public class Main {
    public static void main(String[] args) {
        int[] data = {10, 20, 30};
        System.out.println(data[2]);
        System.out.println(data[3]);
    }
}

Output

30
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Tip: Need a list that can grow? Use ArrayList (covered in the Collections module of the medium level).