Skip to main content
Lesson 19 - Single Dimension Arrays
Lesson MenuPreviousNext
  
Example of an Array page 4 of 11

  1. The following program will introduce you to some of the syntax and usage of the array class in Java:

    Program 19-1

    public class ArrayExample
    {
      public static void main (String[] args)
      {
        int[] A = new int[6];  //  an array of 6 integers
        int loop;
    
        for (loop = 0; loop < 6; loop++)
          A[loop] = loop * loop;
        System.out.println("The contents of array A are:");
        System.out.println();
        for (loop = 0; loop < 6; loop++)
          System.out.print("  " + A[loop]);
        System.out.println();
      }
    }
    
    Run output:
    
    The contents of array A are:
    
      0  1  4  9  16  25
  2. An array is a linear data structure composed of adjacent memory locations, or "cells", each holding values of the same type.

  3. The variable A is an array, a group of 6 related scalar values. There are six locations in this array referenced by index positions 0 to 5. Note that indexes always start at zero, and count up by one's until the last slot of the array. If there are N slots in an array, the indexes will be 0 through N-1.

  4. The variable loop is used in a for loop to reference index positions 0 through 5. In this program the square of each index position is stored in the memory location occupied by each cell of the array. The syntax for accessing a memory location of an array requires the use of square brackets [].

  5. The square brackets [] are collectively an operator in Java. They are similar to the parentheses as they have the highest level of precedence compared to all other operators.

  6. The index operator performs automatic bounds checking. Bounds checking makes sure that the index is within the range for the array being referenced. Whenever a reference to an array element is made, the index must be greater than or equal to zero and less than the size of the array. If the index is not valid, the exception ArrayIndexOutOfBoundsException is thrown.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.