Last Updated : 12 Jul, 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. In this article, we will discuss the New
Different Ways to Add an Element to an ArrayThere are two different approaches we can use to add an element to an Array. The approaches are listed below:
The first approach is that we can create a new array whose size is one element larger than the old size.
Approach:
Example: This example demonstrates how to add an element to an array by creating a new array.
Java
// 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));
}
}
[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.
Approach:
Example: This example demonstrates how to add element to an array using an ArrayList.
Java
// 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));
}
}
[10, 20, 30, 40, 50, 70]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4