Performing a fast array copy

The System class contains a method called arraycopy that copies an array or part of an array to another one. You specify a source array (the elements that are being copied) and a destination array (where the elements should go). You should have allocated enough memory for the destination array to hold the new values. Also, you can specify the source offset that indicates from what index the copying should start and an destination offset that indicates what index the values should be copied to. The types of the source array and destination array should match (eg. you can’t copy elements from an object array into an integer array) or an ArrayStoreException will be thrown.

This example copies 5 elements from arr starting from index 3 into arr2 starting from index 0.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9 };
      int arr2[] = new int[5];
      System.arraycopy(arr, 3, arr2, 0, 5);
 
      System.out.print("arr:nt");
      printArray(arr);
      System.out.print("arr2:nt");
      printArray(arr2);
   }      
 
   public static void printArray(int []arr) {
      for (int i=0; i<arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }
}