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.

14. Element Copied to any Cell

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

Element Copied to any Cell

Of course, the value in a cell of one array can be copied to any cell of another array if the type of the first array can be converted to the type of the second.

In the following, selected ints from an array of ints are copied to various cells in an array of doubles.


class ArrayEg5
{
  public static void main ( String[] args )
  {
    int[] valA = { 12, 23, 45, 56 };

    double[] valB = new double[6];

    valB[ 0 ]  = valA[ 2 ] ;
    valB[ 3 ]  = valA[ 2 ] ;
    valB[ 1 ]  = valA[ 1 ] ;
    valB[ 5 ]  = valA[ 0 ] ;
    
    System.out.println( "valB:" + valB[0] + ", " + valB[1] + ", " + valB[2] + ", " 
      + valB[3] + ", " + valB[4] + ", " + valB[5]  );
   }
}              

Question 14:

Fill in the blanks in the following so that the elements in valA are copied to valB in reverse order:
class ArrayEg6
{
  public static void main ( String[] args )
  {
    int[] valA = { 12, 23, 45, 56 };

    int[] valB = new int[4]; 

     =  ;

     =  ;

     =  ;

     =  ;  

 
   }
}