The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

## Copying Arrays

> Use `System`'s `arraycopy` method to efficiently copy data from one array into another. The `arraycopy` method requires five arguments:

> >     public static
> >         void arraycopy(Object source,
> >                        int srcIndex,
> >                        Object dest,
> >                        int destIndex,
> >                        int length,

> The two `Object` arguments indicate the array to copy from and the array to copy to. The three integer arguments indicate the starting location in each the source and the destination array, and the number of elements to copy. This diagram illustrates how the copy takes place:

> The following program, `ArrayCopyDemo`, uses `arraycopy` to copy some elements from the `copyFrom` array to the `copyTo` array.

> >     public class ArrayCopyDemo {
> >         public static void main(String[] args) {
> >             char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
> >     			    'i', 'n', 'a', 't', 'e', 'd' };
> >             char[] copyTo = new char[7];

> >             System.arraycopy(copyFrom, 2, copyTo, 0, 7);
> >             System.out.println(new String(copyTo));
> >         }
> >     }

> The `arraycopy` method call in this example program begins the copy at element number 2 in the source array. Recall that array indices start at 0, so that the copy begins at the array element 'c'. The `arraycopy` method call puts the copied elements into the destination array beginning at the first element (element 0) in the destination array `copyTo`. The copy copies 7 elements: 'c', 'a', 'f', 'f', 'e', 'i', and 'n'. Effectively, the `arraycopy` method takes the "caffein" out of "decaffeinated", like this:

> Note that the destination array must be allocated before you call `arraycopy` and must be large enough to contain the data being copied.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.