how to add element to end of array java

how to add element to end of array java

To add an element to the end of an array in Java, you can use the Arrays.copyOf method from the java.util package. This method creates a new array that is a copy of the original array, with a specified length that is greater than the original array.

Here's an example of how you could use the Arrays.copyOf method to add an element to the end of an array:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] original = {1, 2, 3};
    int[] expanded = Arrays.copyOf(original, original.length + 1);
    expanded[original.length] = 4;
    System.out.println(Arrays.toString(expanded));
  }
}
Sourc‮www:e‬.lautturi.com

In this example, the Arrays.copyOf method creates a new array expanded that is a copy of the original array, with an additional element at the end. Then, the value 4 is assigned to the last element of the expanded array. Finally, the Arrays.toString method is used to print the expanded array as a string.

The output of this example would be the following array:

[1, 2, 3, 4]

Keep in mind that the Arrays.copyOf method creates a new array, so the original array is not modified. If you want to modify the original array, you can use the System.arraycopy method instead, which copies the elements of one array to another array.

Here's an example of how you could use the System.arraycopy method to add an element to the end of an array:

public class Main {
  public static void main(String[] args) {
    int[] original = {1, 2, 3};
    int[] expanded = new int[original.length + 1];
    System.arraycopy(original, 0, expanded, 0, original.length);
    expanded[original.length] = 4;
    System.out.println(Arrays.toString(expanded));
  }
}

This example uses the System.arraycopy method to copy the elements of the original array to the expanded array, and then assigns the value 4 to the last element of the expanded array.

Keep in mind that both the Arrays.copyOf and the System.arraycopy methods are designed to work with arrays of primitive types, such as int, double, and char. If you want to add an element to the end of an array of objects, you can use a different approach, such as creating a new array and copying the elements manually, or using a collection class, such as ArrayList.

Created Time:2017-11-01 12:05:10  Author:lautturi