OneCompiler

[Java] How to insert an element in the starting of the array?

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

1 Answer

4 years ago by

There is no quick util to perform this operation, we need to loop through the original array and assign values to a new array based on the logic. If the index is 0 then we need to assign the new element.

import java.util.Arrays;

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

		String[] newColors = new String[colors.length + 1];
		newColors[0] = newColor;

		for (int i = 1; i < colors.length + 1; i++) {
			newColors[i] = colors[i - 1];
		}

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

Output:

[brown, blue, red, green, yellow]

Try this code online: https://onecompiler.com/java/3xmtdzsuj

4 years ago by Karthik Divi