Copying Values between Cells

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

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 between Cells

In this example, the int in cell 0 of valA is copied to cell 0 of valB, and so on. 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:

two arrays

Super Bug Alert: The following statement does not do the same thing:

super bugvalB = valA ;

Remember that arrays are objects. The statement above will merely copy the object reference in valA into the object reference variable valB, resulting in two ways to access the single array object:

The object that valB previously referenced is now lost (it has become garbage.)

QUESTION 13:

Say that the statement valB = valA had been executed, resulting in the above picture. What would the following print out?

valA[2] = 999;
System.out.println( valA[2] + "   " + valB[2] );