Arrays

An array is a list of items of the same type in which each item is stored at a specific, numbered position. Arrays are indicated in Java using square brackets ([]).

Example 1: The following declaration creates a reference to an array called salary. The declaration states that salary will only contain double values. The second statement assigns a particular array of 50 double values to salary.
   double[] salary;
   salary = new double[50];
This could also be accomplished in a single statement:
   double[] salary = new double[50]; 

What is an array?

What additional properties do arrays in Java have?

Example 2: Arrays can be initialized to contain specific values:

    int[] coinValues = {1, 5, 10, 25, 50};  // Initializer Lists 
The array coinValues contains 5 integers: the values 1, 5, 10, 25 and 50 respectively.

Example 3: Array values are accessed by giving the array name followed by the position of the item in brackets:
    int x = coinValues[0];
The variable x is one after this statement is executed.

Exercise 1: Let:
   int [] numbers = {5, -30, 20, 1, 7, 0, 22};
Write code segments using the array numbers to do the following:

Use numbers.length rather than explicitly giving the number 7 when you need the length of the array.


Arrays as parameters

Arrays can be designated as parameters by giving the type followed by [] instead of just the type.

Example 4: The printArray method outputs the elements of the array numbers on one line separated blanks.
   public static void printArray(int[] numbers) { 
      for (int k = 0; k < numbers.length; k++) 
          System.out.print(numbers[k] + " "); 
      System.out.println();
   }