Wednesday, 17 December 2014

// The "UsingArraysExample1B" class.  Page 314.
// (from the Carter book)

// Example 1B:  (continued from page 313):
//
// 6. Finally, notice the way we have written the condition
// that controls the for loop:
// as --> 'i < flags.length'.  The value of 'flags.length' is
// the size of the array, or, the number of elements in it.
// 7. As we have already noted, since an array is indexed
// from zero, the index of the last element is one less than
// the value of its length.
// 8. If we were to write the condition as --> 'i <= flags.length',
// we would be trying to access an element that is off the upper bound
// of the array.
// 9. But, if we attempt to use an index value that is out of the range
// of the array, Java 'throws an ArrayIndexOutOfBoundsException'
// (an error message) to let us know what we have done.
// 10. Because arrays, like other objects, are 'reference' types,
// they behave as other objects do when we try to manipulate them.
// 11. For example, suppose we make the declarations below:

public class UsingArraysExample1B
{
    public static void main (String[] args)
    {
        int[] p = {1, 3, 5, 7, 9};
        int[] q = {0, 2, 4, 6, 8};

        // 11 (con'd):
        // if we were now to write this assignment statement:

        p = q;

        // 11 (con'd):
        // this would copy the values from the array cells in q, to the
        // array cells in p.  The effect of this copying would be to have
        // p now refer to the same array values as q.  Since there is no longer
        // any reference to the array of odd numbers, these values are
        // no longer accessible to the program.

    } // main method
} // UsingArraysExample1B class
//
// Example 1B: (continued):
//
// 12. Comparison of arrays is like comparison of other objects in that,
// if p and q are array variables, the expression p == q will be true,
// if and only if, both p and q are referring to same array cells.
// It is NOT, however, a test of EQUALITY of the elements of 2 distinct
// arrays.  If we wanted to test for the equality of the contents of 2
// arrays, we should use a for loop that indexes through the 2 arrays,
// comparing corresponding array pairs for their contents.
// 13. Arrays, like all objects, can be parameters of methods (passed to
// methods as arguments) and returned from methods.

No comments:

Post a Comment