OneCompiler

[Java] How to insert an element at a specific location in an array?

I want to insert an element at a specific index of an array, how to do that in Java?

1 Answer

4 years ago by

We can assign the new element to the array by index. Following code shows how to do that

import java.util.Arrays;

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

		colors[index] = newColor;

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

Output:

[blue, red, brown, yellow]

Try it online here: https://onecompiler.com/java/3xmtf4qnf

4 years ago by Karthik Divi