Java – Add Element to Starting of Array
Java Array, by default, does not support to add or remove an element. Therefore, to add an element to the starting of given array, create a new array with the original size + 1, and then assign the new element to be added, and the elements in the original array to the new array.
Examples
In the following example, we take an integer array and add an element to the starting of the array. We shall write a function addElement(int[] arr, int element)
to return a new array with the element
added to the starting of the array arr
.
Main.java
import java.util.Arrays;
public class Main {
public static int[] addElement(int[] arr, int element) {
int newArr[] = new int[arr.length + 1];
newArr[0] = element;
for (int i = 0; i < arr.length; i++) {
newArr[i + 1] = arr[i];
}
return newArr;
}
public static void main(String[] args) {
int arr[] = {2, 4, 6};
int element = 8;
int newArr[] = addElement(arr, element);
System.out.println("Original : " + Arrays.toString(arr));
System.out.println("New Array : " + Arrays.toString(newArr));
}
}
Output
Original : [2, 4, 6]
New Array : [8, 2, 4, 6]
Based on the datatype of the array, we may modify the addElement() function, or define a new function that overloads this addElement() function.
Conclusion
In this Java Tutorial, we learned how to add an element to the starting of an array with examples.