Arrays

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]; 

     =  ;

     =  ;

     =  ;

     =  ;  

 
   }
}