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


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

1 Answer

3 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 the middle index 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";

		int middleIndex = colors.length / 2;

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

		for (int i = 0; i < colors.length + 1; i++) {
			if (i < middleIndex) {
				newColors[i] = colors[i];

			} else if (i == middleIndex) {
				newColors[i] = newColor;
			} else {
				newColors[i] = colors[i - 1];
			}
		}

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

Output:

[blue, red, brown, green, yellow]

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

3 years ago by Karthik Divi