Manipulating array elements

 

Java treats each array element as a variable, which makes it possible to use any arithmetic or relational operators with arrays elements as operands.   To use array elements as operands, we need to specify the index of the element.  Let’s consider the array numbers from before.  We can assign a new value (say 99) to its first element as follows:

 

      numbers[0] = 99;

 

After the above statement executes, the array will have changed to:

 

      numbers    

 

 


99

3

6

8

11

                    0          1           2           3            4

 

We can also have 2 array elements as operands in an assignment statement:

 

      numbers[2] = numbers[4];

 

This will copy the value at index 4, which is 11, to index 2, replacing the 6.  The array will be:

 

      numbers    

 

 


99

3

11

8

11

                    0          1           2           3            4

 

An array index in Java is not limited to being an integer literal.  We can in fact use a variable as an index into an array as long as the variable is an integer.  The following statements are perfectly valid:

 

      int i = 3;

      System.out.println(numbers[i]);

 

This will print out the value of the element at index 3 (the fourth element in the array, 8).  We can print out the value of the next element with the statement:

 

            System.out.println(numbers[i+1]);  // displays the element at index 4

 

This tells us that we can index an array using an expression, as long as what the expression inside the square brackets evaluates to (in this case i+1 is 4) does not exceed the boundaries of the array (0 to 4). 

 

Array notation can at times get confusing when both the index and the array element itself involve expressions.  Consider the statement:

 

            numbers[i+1]++;

 

Since i is 3, this is equivalent to the statement number[4]++, which simply adds one to the element at index 4.  While the value of the fourth element in the array is changed to 12 (from 11), i’s value remains the same.