Skip to main content
ICT
A16 - Single Dimension Arrays
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

A. Example of an Array page 3 of 10

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

    Code Sample 16-1:

    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 similar to the ArrayList. It 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 indexes 0 to 5. Note that indexes always start at zero, and count up by one until the last slot of the array. If there are N slots in an array, the indexes will be 0 through N-1 (for example, if N=6, the indexes are 0 through 5 or (N-1)).

  4. The variable loop is used in a for loop to reference indexes 0 through 5. In this program, the square of each index 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, and are called the index operator. 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.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.