How to copy array to another array in Java

Copy array to another array in Java

In this example, We will show you simple program about, How to copy array to another array in Java. The example program were tested and shared in the below post.

Example Program

package com.dineshkrish;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class MyArrays {
	
	// method to copy the array
	public static int[] copyOf(int[] oldArray, int newLength) {
		
		// getting the old length of the given array
		int oldLength = oldArray.length;
		
		// creating the array with new length
		int[] newArray = new int[newLength];
		
		for(int i=0;i<oldLength;i++) {
		
			// copying the elements to new array from old array
			newArray[i] = oldArray[i];
		}
		
		return newArray;
	}

	public static void main(String[] args) {
		
		// your array object
		int[] array = {1, 2, 3, 4, 5};
		
		System.out.println("Old Length :"+array.length);
		
		// calling the method
		array = MyArrays.copyOf(array, 10);
		
		System.out.println("New Length :"+array.length);
		
		
		
	}
}

Output


Old Length :5
New Length :10