Arrays
This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.
13. Copying Values from Cell to Cell
Answer:
class ArrayEg4
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];
valB[ 0 ] = valA[ 0 ] ;
valB[ 1 ] = valA[ 1 ] ;
valB[ 2 ] = valA[ 2 ] ;
valB[ 3 ] = valA[ 3 ] ;
}
}
Copying Values from Cell to Cell
valB[ 0 ] = valA[ 0 ] ;
This is just like an assignment statement
spot = source;
where both variables are of primitive
type
int
. After the four assignment statements of the answer have executed, each array contains the same values in the same order:
Super Bug Alert: The following statement does not do the same thing:
valB = valA ;
Remember that arrays are objects. The statement above copies the object reference in valA
into the object reference variable valB
, resulting in two ways to access the array object valA
, as
seen in the second picture.
The object that valB
previously referenced is now lost (it has become garbage.)
valA
and valB
are now aliases for the same object.
The array object previously pointed to by valB
is now garbage (unless there is some other reference variable that points to it.)
Question 13:
Say that the following executes, resulting in the above picture. What is printed out?
valB = valA;
valA[2] = 999;
System.out.println( valA[2] + " " + valB[2] );