View RSS Feed

Java Array

Copying Arrays

Rate this Entry
by , 03-04-2012 at 11:08 AM (510 Views)
An arraycopy method is used by the system class which can efficiently be used to copy one array’s data to other:

Java Code:
public static void arraycopy(Object src,
                       int srcPos,
                       Object dest,
                       int destPos,
                       int length)
The array to copyfrom or the array to copyto is specified by the two object arguments. Three int arguments are used for the specification of the number of array elements to copy, starting position in the destination array and the starting position in the source array.

Given program named as ArrayCopyDemo is used to make the declaration of the array of char elements by spelling “decaffeinated”. For copying array component subsequence to another array, arraycopy is used.

Java Code:
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));
This program’s output is:


Submit "Copying Arrays" to Facebook Submit "Copying Arrays" to Digg Submit "Copying Arrays" to Submit "Copying Arrays" to StumbleUpon Submit "Copying Arrays" to Google