Academic Java    Java Tutorial  >  Arrays  >  creating and initialization

creating and initialization Example

The program shows arrays ia and ib being created.

Notice that indexing of an array starts at zero.

Array ic is initialized with values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Array Intitialization Example
class ArayInitializationExample {

   public static void main(String[] args) {

      int[] ia;
      ia = new int[2];

      int[] ib = new int[2];

      int[] ic = {12,20,17};

   }
}

6 An array is declared.

7 The new keyword instructs the compiler to reserve space for the array; the number in the square brackets indicates how many elements are to be created, i.e. its length.
Each element is addressed with an index between the square brackets. Indexing starts at zero. Each element has a default value of 0.

9 The previous two lines for ia can be combined in one, like this, to accomplish the same thing i.e. an array definition.

11 An array ic is initialized. The curly braces contain values, the number of which determines the array's length.
Notice how elements have been initialized from the values, starting at index 0.