arraycopy method in java

Hi everyone, its been a long time since I posted. So here is a new one. In this blogpost, I will writing about arraycopy() in java. Its a common interview question these days. It copies an array from specified source array, beginning at the specified position to the specified position of destination array.

arraycopy() has got 5 parameters. They are:

1) src - The source array
2) srcPos - The position in source array from where the elements are copied
3) des - The destination array
4) desPos - The position in destination array where the elements copied from source array is pasted.
5) length - Number of elements to be copied from source array.

Please check the below program to understand more about arraycopy().

package com.techjourney.methods;

public class ArrayCopyMethod {

    public static void main(String args[])
    {
        int sourceArray[] = new int[]{1,2,3,4,5,6};
        int destinationArray[] = new int[]{7,8,9,10,11,12,13,14,15};
        
        System.arraycopy(sourceArray, 0, destinationArray, 0, 3);
        
        System.out.println(" The contents of destination array are as follows: ");
        
        for(int i=0;i<destinationArray.length;i++)        {
            System.out.print("\t");
            System.out.print(destinationArray[i]);
        }
        
    }
}

In the above program, the first three elements from the source array are copied and in destination array, the first three elements are replaced.

The output of the program is as follows:

The contents of destination array are as follows: 
    1    2    3    10    11    12    13    14    15


arraycopy() should be used carefully, as it will arise exceptions like IndexOutOfBoundsException (when the length specified exceeds the array length) and ArrayStoreException (type mismatch between source and destination array).

That is all from arraycopy() method. I hope everyone liked this post. Please comment below if you have any queries or thoughts.

Thank you for reading the post.

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++