Copy Java array with System.arraycopy

If you want to copy the elements from one array to another array then you can use the System.arraycopy method to do so.


public class ArrayCopyDemo {

	public static void main(String[] args) {
		String[] hello = { "hello", "world!" };
		String[] helloCopy = new String[hello.length];
		System.arraycopy(hello, 0, helloCopy, 0, hello.length);
		System.out.println(helloCopy[0] + " " + helloCopy[1]);



Above program will output “Hello World!” on the screen. System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) takes in an array object and copy it’s elements to the destination array object, you will need to specify the beginning position of the element for both the original array and the destination array which will be 0 if you wish to copy all the elements in an array starting from the beginning.

Like this post? Kindly share!