How to append to an array in Java

Key takeaways:

  • In Java, arrays cannot grow once created, so adding elements requires workarounds.

    • Method 1: Arrays.copyOf() method creates a new, larger array, copies the original data, and adds the new element at the end.

    • Method 2: ArrayUtils.add() is a part of Apache Commons Lang. This method abstracts the resizing process, making code cleaner and more readable.

    • Method 3: ArrayList.add() allows dynamic resizing. It can grow and shrink automatically without manual resizing.

Think about a box where you keep your favorite things—maybe books, gadgets, or notes. This box has a fixed size, but over time, you start collecting more stuff and need to add more space. Now, what if I told you that in programming, arrays are like that box, and they don’t automatically grow as you need them to?

In Java, arrays are great for storing data, but sometimes you want to add more items after you’ve already set things up. The question is: how do you add things to your array without breaking it? That’s where this Answer comes in!

Java arrays

Java arrays can’t grow once they have been created; so, to add an element, you need to use the one of the following methods:

  • Using Arrays.copyOf()
  • Using ArrayUtils.add() (Apache Commons Lang)
  • Using ArrayList.add()
svg viewer

Method 1: Using Arrays.copyOf() to append an element

One of the most common ways to append an element to an array is by using the Arrays.copyOf() method, which creates a new array with a larger size and copies the original array’s elements into it.

Steps to append an element using Arrays.copyOf():

  • Create a new larger array: The new array should have a size greater than the original one by 1.
  • Copy over the content: Use Arrays.copyOf() to copy all elements of the original array into the new one.
  • Insert the new element: Add the new element to the last position of the new array.
import java.util.Arrays;
class ArrayAppend {
public static void main( String args[] ) {
int[] arr = { 10, 20, 30 };
System.out.println(Arrays.toString(arr));
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = 40; // Assign 40 to the last element
System.out.println(Arrays.toString(arr));
}
}

In line 8, a copy of arr is made with one extra slot. The new array is assigned to arr, replacing the original array.

Method 2: Using ArrayUtils.add() (Apache Commons Lang)

If you have Apache Commons Lang on your classpath, you can use the ArrayUtils.add() method to append an element to an array in a more readable and simplified way. This method performs the same operations under the hood as Arrays.copyOf(), but it abstracts the details, making your code cleaner.

int[] arr = { 10, 20, 30 };

arr = ArrayUtils.add(arr, 40);

Under the hood, add performs the same three steps described in the beginning. It just makes the process more readable.

Method 3: Using ArrayList to append an element

While arrays are great for storing data in Java, they have a fixed size. If you find yourself frequently appending elements, using an ArrayList is often a better solution. ArrayLists are dynamic, meaning they can grow and shrink as needed.

import java.util.ArrayList;
import java.util.Arrays;
class ArrayListAppend {
public static void main(String[] args) {
// Create an ArrayList and add elements
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(10, 20, 30));
// Append 40 to the ArrayList
arr.add(40);
// Print the updated ArrayList
System.out.println(arr); // Output: [10, 20, 30, 40]
}
}

Conclusion

Appending elements to an array in Java isn’t as straightforward as it seems due to the fixed size of arrays. However, there are several ways to add new elements, depending on your requirements:

  • Use Arrays.copyOf() when we need to stick with arrays and resize manually.

  • Use ArrayUtils.add() if we have Apache Commons Lang in your project, this method provides a cleaner, more readable solution.

  • Use ArrayList.add() If we need a dynamic data structure that can grow and shrink automatically, ArrayList is the best option.

Kickstart your programming journey with "Learn Java." Master essential concepts like input/output methods, user-defined methods, and basic data types. Build sequential, selective, and iterative programs through engaging hands-on projects.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can we append two arrays in Java?

We can append two arrays using Arrays.copyOf() in Java:

  • Create a new array with the combined length of both arrays.
  • Copy the elements of the first array into the new array.
  • Copy the elements of the second array into the new array starting after the last element of the first array.

Can I directly append an element to an array in Java?

No, arrays in Java have a fixed size once they are created, so we cannot append elements directly.


Can I append multiple elements to an array at once?

We can loop through elements and append them one by one, or use ArrayUtils.addAll() method to append multiple elements at once.


Free Resources

Attributions:
  1. undefined by undefined