The Wayback Machine - https://web.archive.org/web/20241227194713/https://www.geeksforgeeks.org/how-to-add-an-element-to-an-array-in-java/
Open In App

How to Add an Element to an Array in Java?

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of size n, the task is to add an element x in this array in Java. The size of the array cannot be changed dynamically in Java, as it is done in C/C++.

Example:

Input: arr = [ 1 , 2 , 3 , 4 , 5 ] 
element = 7 Output: [ 1 , 2 , 3 , 4 , 5 , 7 ]

Program:

Java
// Java Program to add an element in an Array
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
   // 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[] = { 1, 2, 3, 4, 5};
       int x = 7;
 
       // call the method to add x in arr
       arr = addX(n, arr, x);
 
       System.out.println(Arrays.toString(arr));
   }
}

Output
[1, 2, 3, 4, 5, 7]

Explanation of the above Program:

  • Create a new array of size n+1, where n is the size of the original array.
  • Add the n elements of the original array in this array.
  • Add the new element in the n+1 th position.
  • Print the new array.

Adding elements to an array is a common task, and understanding the best approach can optimize your program’s performance. To explore more about array manipulations and dynamic resizing techniques, the Java Programming Course provides detailed lessons with hands-on exercises.

Using ArrayList as Intermediate Storage

  • Create an ArrayList with the original array, using asList() method.
  • Simply add the required element in the list using add() method
  • Convert the list to an array using toArray() method

Example:

Java
// Java Program to add an element in an Array
import java.io.*;
import java.lang.*;
import java.util.*;

class GFG {

    // 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[] = { 1, 2, 3, 4, 5};
        int x = 7;

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

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

Output
[1, 2, 3, 4, 5, 7]


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg