[Java] How to insert an element at the end of the array?


I want to insert a new element at the ending of an array, how to do that in Java?

1 Answer

3 years ago by

We can use Arrays.copyOf to create a new Array with size which is +1 from the original array and then we can insert the new element at the end index of new array.

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		String[] colors = { "blue", "red", "green", "yellow" };
		String newColor = "brown";

		String[] newColors = Arrays.copyOf(colors, colors.length + 1);

		newColors[newColors.length - 1] = newColor;

		System.out.println(Arrays.toString(newColors));
	}
}

Output:

[blue, red, green, yellow, brown]

try this code online here https://onecompiler.com/java/3xmtev4ua

3 years ago by Karthik Divi