Java Tutorial: Arrays

, , …,

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.

To declare a array type, the syntax is: type or class name[] myArray = ….

To create a initial array, the syntax is: myAarray = new type or class[n];.

After a array is created, you need to assign value to each slot. Like this: myArray[3] = 7;.

If a array slot isn't initialized, its value is garbage.

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.println();
        System.out.print(myA[0].length); // prints the length of a row
    }
}

Note: list-like things such as general lists, vectors (tuple), keyed-lists (hash table, associative array), and may other types are in the package “java.util.Collections”. Collection (Java Platform SE 8 )

blog comments powered by Disqus