How to Copy an Array in Java?

The System.arraycopy  method copies an array from the source array, beginning at the specified position, to the specified position of the destination array.

				
					import java.util.Arrays;

public class ArrayCopy {
	static int a[] = { 1, 2, 3, 7 };
	static int b[] = { 4, 5, 6, 7 };

	public static void main(String[] args) {
		int c[] = add(a, b);
		System.out.println(Arrays.toString(c));
	}

	private static int[] add(int[] c2, int[] b2) {
		int p[] = new int[c2.length + b2.length];
		System.arraycopy(c2, 0, p, 0, c2.length);
		for (int i = 0; i < b2.length; i++) {
			p[c2.length + i] = b2[i];
		}
		return p;
	}
}
				
			

Output :-
[1,2,3,7,4,5,6,7]

Leave a Comment

Your email address will not be published. Required fields are marked *