In Java, arrays are used to store multiple values of the same type in one variable. But the problem with arrays is that their size cannot change once created. This makes it hard when you want to add more elements. In this article, we will learn how to Add Elements in Array in Java in different ways, such as making a new array, using System.arraycopy(), or using an ArrayList. With simple examples, you will understand how to manage arrays better in your Java programs.

Understanding Arrays in Java

Before we dive into looking at how to Add Elements in Array in Java, let's briefly review what arrays are in Java. An array is a collection of elements, all of the same type, stored in contiguous memory locations. The size of an array is fixed once it is created, meaning you cannot change its size dynamically. This is a key point to remember when working with arrays in Java.

Declaring and Initializing Arrays

In Java, you can declare an array using the following syntax:

dataType[] arrayName;

For example, to declare an array of integers:

int[] numbers;

You can also initialize an array at the time of declaration:

int[] numbers = {1, 2, 3, 4, 5};

Accessing Array Elements

You can access elements in an array using their index, which starts at 0. For example, to access the first element of the numbers array:

int firstNumber = numbers[0]; // This will be 1

How to Add Elements to an Array in Java

Since arrays in Java have a fixed size, adding elements to an existing array requires some additional steps. Below are several methods to add elements to an array in Java, along with an easier approach using an ArrayList for how to Add Elements in Array in Java:

Method 1: Using a New Array

The most straightforward way to add an element to an array is to create a new array with a larger size and copy the existing elements along with the new element.

Code Example

public class AddElementToArray {

    public static void main(String[] args) {

        int[] originalArray = {1, 2, 3, 4, 5};

        int newElement = 6;

        // Create a new array with one extra size

        int[] newArray = new int[originalArray.length + 1];

        // Copy elements from the original array

        for (int i = 0; i < originalArray.length; i++) {

            newArray[i] = originalArray[i];

        }

        // Add the new element

        newArray[newArray.length - 1] = newElement;

        // Print the new array

        for (int num : newArray) {

            System.out.print(num + " ");

        }

    }

}

Explanation

In this example, we create a new array called newArray that is one element larger than the originalArray. We then copy the elements from originalArray to newArray and add the new element at the end. Finally, we print the new array.

Method 2: Using System.arraycopy()

Java provides a built-in method called System.arraycopy() that can be used to add element to array in Java from one array to another. This method is more efficient than manually copying elements in a loop.

Code Example

public class AddElementToArray {

    public static void main(String[] args) {

        int[] originalArray = {1, 2, 3, 4, 5};

        int newElement = 6;

       // Create a new array with one extra size

        int[] newArray = new int[originalArray.length + 1];

        // Use System.arraycopy to copy elements

        System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);

        // Add the new element

        newArray[newArray.length - 1] = newElement;

        // Print the new array

        for (int num : newArray) {

            System.out.print(num + " ");

        }

    }

}

Explanation

In this example on how to Add Elements in Array in Java, we use System.arraycopy() to copy the elements from originalArray to newArray. The parameters specify the source array, the starting index in the source array, the destination array, the starting index in the destination array, and the number of elements to copy.

Method 3: Using ArrayList

If you find yourself frequently needing to add a new element to array in Java, consider using an ArrayList instead of an array. ArrayList is a resizable array implementation of the List interface, which allows you to add and remove elements dynamically.

Code Example

import java.util.ArrayList;

public class AddElementToArrayList {

    public static void main(String[] args) {

        ArrayList<Integer> numbers = new ArrayList<>();

        // Adding elements to the ArrayList

        numbers.add(1);

        numbers.add(2);

        numbers.add(3);

        numbers.add(4);

        numbers.add(5);

        // Adding a new element

        numbers.add(6);

        // Print the ArrayList

        for (int num : numbers) {

            System.out.print(num + " ");

        }

    }

}

Explanation

In this example, we create an ArrayList called numbers and add elements using the add() method. This method allows us to add elements dynamically without worrying about the size of the collection.

Method 4: Adding Multiple Elements to an ArrayList

If you need to add multiple elements at once and you are thinking about how to add multiple elements in arraylist in Java, then you can use the addAll() method of the ArrayList class.

Code Example

import java.util.ArrayList;

import java.util.Arrays;

public class AddMultipleElementsToArrayList {

    public static void main(String[] args) {

        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        // Adding multiple elements

        numbers.addAll(Arrays.asList(6, 7, 8));

       // Print the ArrayList

        for (int num : numbers) {

            System.out.print(num + " ");

        }

    }

}

Explanation

In this example, we initialize the ArrayList with some elements using Arrays.asList(). We then add multiple elements at once using the addAll() method.

Conclusion

In Java, you can add elements to an array in different ways. You can create a new array and copy elements, use System.arraycopy() for faster copying, or use an ArrayList for flexible resizing. Arrays have a fixed size, but an ArrayList can grow as needed, which makes it very useful. So, by learning these methods of how to Add Elements in Array in Java, you can easily manage data in your programs. Try the examples to practice and see which method works best for you. For a structured learning path and more Java programming concepts, enroll in our java full stack course to build your skills from basics to advanced topics.

Frequently Asked Questions (FAQs)
Q. How does add() work in Java?

Ans. The add() method in Java is used with collections like ArrayList to insert elements either at the end or at a specific index, shifting other elements automatically.

Q. How to use sum() in Java?

Ans. The sum() method is not built-in. But you can use IntStream.sum() or loops to calculate the total of elements in an array, list, or collection.