Some Misc Notes
← prev | next →     Top-level ToC     /java/examples/arrays.html     (printable version)

Java arrays are not resizable. If you want “resizable arrays”, use an ArrayList (see Data Structures examples).

import java.util.Arrays;

int[] ia = new int[100];
int[] ia = {1, 2, 3};
ia[1];       // ==> 2
ia[1] = 55;  // Now: 1, 55, 3
ia.length;   // ==> 3

// Looping over an array.
for (int i : ia) {
    // ...
}

// Or, ye olde style:
for (int i = 0; i < ia.length; i++) {
    // ...
}

// An anonymous array:
new int[] {1, 2, 3}

// An array of arrays:
int[][] the_matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
};

// To copy an array:
int[] ia_2 = Arrays.copyOf(ia);
// In olden times, folks used System.arraycopy for that.

// To print an array:
System.out.println(Arrays.toString(ia));

See also other static methods in java.util.Arrays.