Java copy array

Java copy array

copying arrays using arraycopy() method in Java:

refe‮al:ot r‬utturi.com
arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Parameters:

  • src the source array.
  • srcPos starting position in the source array.
  • dest the destination array.
  • destPos starting position in the destination data.
  • length the number of array elements to be copied.

example:

/**
 * @author lautturi.com
 * Java example: Copying Arrays Using arraycopy() method Java
 */

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {

		String[] oldArray = {"hello","lautturi","java","python","world","lau"};
		
		int srcPos = 1;
		int destPos = 0;
		int length = 3;
		
		String[] newArray = new String[length];
		System.arraycopy(oldArray, srcPos,newArray, destPos, length);
		
		System.out.println("oldArray:"+Arrays.toString(oldArray));
		System.out.println("newArray:"+Arrays.toString(newArray));

	}
}

output:

oldArray:[hello, lautturi, java, python, world, lau]
newArray:[lautturi, java, python]
Created Time:2017-09-04 07:03:55  Author:lautturi