valA[2] = 999; System.out.println( valA[2] + " " + valB[2] );
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
Of course, the value in a cell of one array can be copied to any cell of another array if the types are compatible.
In the following, selected int
s from an array of int
s
are copied to various cells in an array of double
s.
The int
values are converted to double
values
when they are copied into the array.
public 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] ); } }
valB:45.0, 23.0, 0.0, 45.0, 0.0, 12.0
Fill in the blanks in the following so that the elements in valA
are copied to valB
in reverse order: