Declaring and initializing an array

 

An array declaration includes the data type of its elements and a set of square brackets ‘[]’ to distinguish it from a variable declaration of a simple data type.  If the array elements are known at the time the array is declared (as opposed to them being computed in the program), these values can be listed in a set of curly braces ‘{}’, and are separated by commas.  The syntax for declaring and initializing an array is:

 

      dataType[] arrayVariable = {value1, value2, …, valueN};

 

A statement to declare an array of integers with the values 2, 3, 6, 8, and 11 would be:

 

      int[] numbers = {2, 3, 6, 8, 11};

 

The variable numbers is a reference to a collection of the 5 integer values between the curly braces. 

 

Declaring and initializing an array of a different type follows the same form.  The statement

 

      char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};

 

creates an array of characters referenced by the variable vowels.  The array values are surrounded by single quotes since they are characters.  An array can also hold more complex values such as Strings.  Here’s an example:

 

      String[] rivers = {“Amazon”, “Nile”, “Yangtze”, “Congo”};

 

To obtain the number of elements in an array, we can use the length field along with the array reference:

 

      System.out.println(numbers.length); // length is a field, not a

method

 

      System.out.println(rivers.length);

           

The first statement will output 5, the number of element in the numbers array, while the second will output 4, the number of rivers listed between the curly braces.