How to add new elements to an array in Java?

To add new elements to an array in Java, you have a few options:

  1. If you know the size of the array in advance and the array is not full, you can simply assign a new value to an unused element in the array. For example:
int[] array = new int[10];
array[0] = 1;
array[1] = 2;
array[2] = 3;

This creates an array with three elements: 1, 2, and 3.

  1. If you need to add an element to the end of the array and you don't know the current size of the array, you can use a List instead. The ArrayList class is a resizable array that allows you to add and remove elements as needed. Here's an example:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

This creates a list with three elements: 1, 2, and 3.

  1. If you need to add an element to the end of an array and you don't know the current size of the array, you can use a List as a temporary buffer and then copy the elements back to an array. Here's an example:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
}

This creates an array with three elements: 1, 2, and 3.

Note that once you create an array, its size cannot be changed. If you need to add elements to an array, you will need to create a new array with the desired size and copy the elements from the old array to the new array.