Java Program to double the size of an array


To double the size of an array, let us first create an array −

int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};

Now, get the length of the above array −

int len = arr.length;

Double the size of the above array −

intnewArray[] = new int[len*2];

Now, newArray[] will be having twice the length of the array arr[].

Example

public class Demo {
   public static void main (String args[]) {
      int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
      System.out.println("Length of initial array = " + arr.length);
      int len = arr.length;
      int newArray[] = new int[len*2];
      System.arraycopy(arr, 0, newArray, 0, len);
      System.out.println("Length of new array = "+newArray.length);
   }
}

Output

Length of initial array = 10
Length of new array = 20

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements