Creating an array in Java is a two step process. First
an array variable is declared. For example, this Java
line declares a to be an array of int.
int[] a;
(The left and right
brackets [] signifiy an array
declaration.) Next space for the array must be created.
The following line creates an int array with five elements:
a = new int[5];
This creates an array a with indices 0, 1, 2, 3, 4.
As in the case of objects, the array declaration and
space allocation can be combined into one line
int[] a = new int[5];
After the array has been created, values can be assigned
to the array elements. After the assignment statement
in the left column, the remaining columns show the array
name, index, and value after the assignment expression has
been performed.
Assignment Expression | Array Name | Index | Value |
---|---|---|---|
a[0] = 4; | a | 0 | 4 |
a[1] = 7; | a | 1 | 7 |
a[2] = 6; | a | 2 | 6 |
a[3] = 1; | a | 3 | 1 |
a[4] = 2; | a | 4 | 2 |
Here is an example of an expression that gets values from an array:
System.out.println(a[1] + a[3]);
The value printed is 7 + 1 = 8.
You may be wondering why we don't just use simple variable names like
a0, a1, a2, a3, a4. This works okay if we only have five variables
because if, for example, we want to print the values of these variables,
we can print them as
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
System.out.println(a5);
However, if we have 1,000 variables, this approach is too cumbersome.
We need a variable index so we can print the values in a for loop:
for(i = 0; i <= 999; i++)
    System.out.println(a[i]);
String a = new String("apple");
and a short version
String a = "apple";
Similarly, there is a long version and a short version to
declaring, allocating memory, and assigning values.
The long version is
int[] a = new int[5];
a[0] = 4;
a[1] = 7;
a[2] = 6;
a[3] = 1;
a[4] = 2;
The short version is
int[] a = {4, 6, 7, 1, 2};
String b[] = {"apple", "orange", "peach", "pair"};