valA[2] = 999;
System.out.println( valA[2] + "   " + valB[2] );

Answer:

Since valA and valB both refer to the same object, valA[2] and valB[2] are two ways to refer to the same cell. The statements print out:

999    999

End of the Chapter

Here is a list of facts about arrays. You may wish to refer back to a page that discusses a particular fact in greater detail.

  1. An array is an object that has room for several values, all of the same type.

  2. Each value is stored in a cell of the array. The values stored in an array are sometimes called the elements of the array.

  3. If there are N cells in the array, the cells are indexed from 0 up to (N-1).

  4. The index must be an integer value (byte, short, or int).

  5. An array declaration looks like:

        int[] intArray;
        

    This declaration declares the array reference intArray. It does not create the actual object.

  6. An array can be declared and constructed in a combined statement:

        int[] intArray = new int[17];
        

    This declaration declares the array reference intArray, and constructs an array object containing 17 cells that can hold int.

  7. When an array object is constructed using the new operator, the cells are initialized to the default value of the type of the cell. Numeric types are initialized to zero.

  8. Once an array object has been constructed, the number of cells it has can not be changed. (However, a completely new array object, with a different number of cells, can be constructed to replace the first array object.)

  9. A subscripted variable such as intArray[12] can be used anywhere an ordinary variable of the same type can be used.

  10. The index used with an array can be stored in a variable, for example

        int j = 5 ;
        intArray[ j ] = 24;  // same as: intArray[ 5 ] = 24
        
  11. The index used with an array can be computed in an expression, for example

        int j = 5 ;
        intArray[ j*2 + 3 ] = 24;  // same as: intArray[ 13 ] = 24
        
  12. The index used with an array must be within the range 0..(N-1) where N is is number of cells of the array.

  13. If an index that is out of bounds is used with an array, an exception is thrown and the program stops running (unless it catches the exception.)

  14. An array can be declared, constructed, and initialized using an initializer list. This can only be done when the array is first declared.

Arrays can be confusing at first. But they are very important. If you are somewhat uncertain about arrays, take a break. Then, sometime later, come back to this chapter and work through it again.

The next chapter will discuss further aspects of arrays.

You have reached the end of the chapter.

go to previous page   go to home page