Java: Arrays

By Xah Lee. Date: . Last updated: .

This page shows how to create array in Java.

Array in Java is like a fixed number of slots, each slot holds a item, and all of them the same type.

Here's a example.

/* 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[] myA;

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

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

        // myA.length returns number of items
        System.out.print(myA.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 < myA.length; i++) {
            System.out.print(myA[i] + " ");
        } // prints 0 0 0 7 0 0 0 0 0 0

Things to remember:

Note that code like int[10] myArray; is illegal.

Assign Array Slots Shortcut

You can use this shortcut syntax int[] myArray = {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[] myA = {3,7,4};
        for (int i = 0; i < myA.length; i++) {
            System.out.print(myA[i] + " ");
        } // prints 3 7 4

2-Dimensional Arrays

The syntax to declare 2-dimensional array is this type_or_class[][].

public class Ar2 {
    public static void main(String[] args) {

        // declaring that myA is a 2-dimensional array
        int[][] myA;

        // give the variable a value, and declare its dimensions.
        myA = new int[3][2];

        // assign a value to a array slot
        myA[0][0] = 6;

        System.out.print(myA[0][0]); // prints the value of a slot
        System.out.print(myA[0].length); // prints the length of a row

Note: list-like things such as lists, hash table, see Java: Collection, Map.

Jagged Arrays

You can create a 2D array with m rows and each row have different number of slots.

Java: Jagged Arrays

Array of Objects

Array element can be any object.

See: Java: Array of Objects.

Resizable Array

Array cannot be resized (cannot add element).

If you want to be able to resize array, use ArrayList. See: Java: Collection, Map