Java: Array

By Xah Lee. Date: . Last updated: .

What is Array

/* example showing array declaration, initialization, and filling out the slots. */
public class Ar {
    public static void main(String[] args) {

        // declare var that's array of int datatype
        int[] xx;

        // assign the array int items, 10 of them
        xx = new int[10];

        // array assignment for each slot is like this:
        xx[3] = 7;
        System.out.print(xx[3] + "\n"); // prints 7

        // xx.length returns number of items
        System.out.print(xx.length + "\n"); // prints 10

        // if a array slot has not given a value, it is garbage.
        // In this specific case, java fills it with 0.
        for (int i = 0; i < xx.length; i++) {
            System.out.print(xx[i] + " ");
        } // prints 0 0 0 7 0 0 0 0 0 0
    }
}

Array Syntax

Assign Value to Array Slots

Note that code like int[10] varName; is invalid.

Declare and Initialize Array, Syntax Shortcut

You can use this shortcut syntax int[] xx = {3,7,4}; to declare and initialize array at the same time

// example of array
public class Aj {
    public static void main(String[] args) {
        int[] xx = {3,7,4};
        for (int i = 0; i < xx.length; i++) {
            System.out.print(xx[i] + " ");
        } // prints 3 7 4
    }
}

Resizable Array

If you want to be able to resize array, use ArrayList.

Java, data structures, array, collection, map