How to add data to an array in Java?

In Java, you can add data to an array using the following method:

  1. Add elements one by one using loops: You can iterate through an array using either a for loop or a forEach loop, and then use an assignment statement to add the element to each position in the array.
int[] array = new int[5];
for (int i = 0; i < array.length; i++) {
    array[i] = i + 1;
}
  1. Direct assignment: when initializing an array, you can directly specify the elements in the array within curly braces.
int[] array = {1, 2, 3, 4, 5};
  1. By using the copyOf method of the Arrays class, you can copy elements from one array to another while also specifying the length of the new array.
int[] array1 = {1, 2, 3};
int[] array2 = Arrays.copyOf(array1, array1.length + 1);
array2[array1.length] = 4;
  1. Using the ArrayList class: You can dynamically add elements with the ArrayList class and then convert it into an array.
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Integer[] array = list.toArray(new Integer[0]);

Note: Once an array is created, its length is fixed and cannot add or remove elements directly. If you need to dynamically add or remove elements, you can use the ArrayList class or other collection classes.

bannerAds