Copy Method

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:

The complete program is below.

Copy Method

The copy() method assumes that both arrays are the same size. If not, the program will not work correctly. A better written method would include error checking.

// Array Example
//
class ChangeArray
{
  void print ( int[] x )
  {
    for (int j=0; j < x.length; j++)
      System.out.print( x[j] + " " );
    System.out.println( );
  }

  // Copy source to target
  void copy (int[] source, int[] target)
  {    
    for (int count=0; count<source.length; count++)
      target[ count ] = source[ count ]; 
  }
}

class ChangeTest
{
  public static void main(String[] args)
  {
    ChangeArray cng = new ChangeArray();
    int[] s = {27, 19, 34, 5, 12} ;
    int[] t = new int[ s.length ];
    
    cng.copy( s, t );
    System.out.println( "After copy:" );
    cng.print( t );
  }
}

QUESTION 14:

Here is another version of the copy() method. Is this version correct?

  // Copy source to target
  void copy ( int[] source, int[] target )
  {
    target = source ;
  }