How to Add an Element to an Array in Java? (original) (raw)

Last Updated : 16 Oct, 2025

In Java, **arrays are of fixed size, and we can not change the size of an array dynamically. We have given an array of size **n, and our task is to add an element **x into the array.

There are two different approaches we can use to **add an element to an Array. The approaches are listed below:

**1. Adding an Element Using a New Array

The first approach is that we can create a new array whose size is one element larger than the old size.

// Java Program to add an element // into a new array import java.io.; import java.lang.; import java.util.*;

class Geeks {

// Function to add x in arr public static int[] addX(int n, int arr[], int x) {

   int newarr[] = new int[n + 1];

   // insert the elements from
   // the old array into the new array
   // insert all elements till n
   // then insert x at n+1
   for (int i = 0; i < n; i++)
       newarr[i] = arr[i];

   newarr[n] = x;

   return newarr;

}

public static void main(String[] args) {

   int n = 5;
   int arr[] = { 10, 20, 30, 40, 50};
   int x = 70;

   // call the method to add x in arr
   arr = addX(n, arr, x);

   System.out.println(Arrays.toString(arr));

} }

`

Output

[10, 20, 30, 40, 50, 70]

**2. Using ArrayList as Intermediate Storage

The second approach is we can use ArrayList to add elements to an array because ArrayList handles dynamic resizing automatically. It eliminates the need to manually manage the array size.

// Java Program to add an element in an Array // with the help of ArrayList

import java.io.; import java.lang.; import java.util.*;

class Geeks {

// Function to add x in arr
public static Integer[] addX(int n, Integer arr[], int x)
{
    List<Integer> arrlist = new ArrayList<Integer>(Arrays.asList(arr));

    // Add the new element
    arrlist.add(x);

    // Convert the Arraylist to array
    arr = arrlist.toArray(arr);

    return arr;
}

public static void main(String[] args)
{

    int n = 10;
    Integer arr[] = { 10, 20, 30, 40, 50};
    int x = 70;

    // call the method to add x in arr
    arr = addX(n, arr, x);

    System.out.println(Arrays.toString(arr));
}

}

`

Output

[10, 20, 30, 40, 50, 70]