Java program to double the size of an array


In this article, we will learn how to double the size of an array in Java. This involves creating a new array with twice the length of the original array and copying the elements from the original array to the new, larger array.

Problem Statement

Create an initial array with predefined integer values and determine its length. Then, create a new array with double the length of the original array, copy the elements from the original array to the new one, and print the lengths of both the original and the new arrays to verify the resizing operation.

Steps to Double the Size of an Array

Following are the steps to double the size of an array -

  • Step 1: Initialize the array.
  • Step 2: Print the length of the initial array.
  • Step 3: Double the size of the array.
  • Step 4: Copy elements to the new array.
  • Step 5: Print the length of the new array.

Java Program to Double the Size of an Array

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

Code Explanation

The class Demo is defined with a main method, which is the entry point of the application. The line given below initializes an array arr with ten integer values and print the length of the original array arr and print the length of the new array.

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

By using the below statement we can determine the length of the original array in the variable len.

int len = arr.length;

We will create a new array newArray with twice the length of the original array −

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

And copies all elements from the original array arr to the new array newArray after this we will print the length of the new array to confirm it is twice the length of the original array.

Updated on: 02-Jul-2024

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements