How to Copy and Resize Array Dynamically in Java


In this example, let’s see how to copy and resize array dynamically.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class CopyArray {

	public static void main(String[] args) {
		
		int[] intArray = {1,2,3,4,5,6};
		System.out.println("Before copy array size  is : " + intArray.length);
		
		/*
		 * Use the method Arrays.copyOf() 
		 * to create new array with new size 
		 * and copy old arrays content to the new array.
		 */
		int[] newIntArray = Arrays.copyOf(intArray, 15);
		System.out.println("After copying new array size is : " + newIntArray.length);

	}

}

Output:

Before copy array size  is : 6
New array size after copying: 15

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments