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

A good answer might be:

Since valA and valB both refer to the same object, valA[2] and valB[2] are two ways to refer to the same slot. 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 slot of the array.

  3. If there are N slots in the array, the slots 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 slots that can hold int.

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

  8. Once an array object has been constructed, the number of slots it has can not be changed. (However, a completely new array object, with a different number of slots, 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 slots 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.



Click here     Back to the main menu.

You have reached the end of the chapter.