Remove first element from array in Java
This post will discuss how to remove the first element from an array in Java.
Since the length of an array is fixed in Java, there is no standard way to remove the first element from it. However, you can create a new array containing all the original array elements except the first element. There are several ways to do that:
1. Using Arrays.copyOfRange() method
The idea is to use the Arrays.copyOfRange() method, to get a subarray of the original array. Java has overloaded versions of this method for all primitive types and objects. Its usage is demonstrated below for a primitive int array:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; public class Main { public static int[] removeFirstElement(int[] arr) { return Arrays.copyOfRange(arr, 1, arr.length); } public static void main(String[] args) { int[] arr = {2, 3, 4, 8, 7, 1}; arr = removeFirstElement(arr); System.out.println(Arrays.toString(arr)); } } |
Output:
[3, 4, 8, 7, 1]
2. Using System.arraycopy() method
Another solution is to allocate a new array of size one less than the original array and then call the System.arraycopy() method, which copies the specified range from the original array to the new array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; public class Main { public static int[] removeFirstElement(int[] arr) { int[] result = new int[arr.length - 1]; System.arraycopy(arr,1, result,0, arr.length - 1); return result; } public static void main(String[] args) { int[] arr = {2, 3, 4, 8, 7, 1}; arr = removeFirstElement(arr); System.out.println(Arrays.toString(arr)); } } |
Output:
[3, 4, 8, 7, 1]
3. Using IntStream.range() method
With the introduction of Stream with Java 8, you can get the sequential ordered stream between two indexes, and convert it back to an array using the toArray() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Arrays; import java.util.stream.IntStream; public class Main { public static int[] removeFirstElement(int[] arr) { return IntStream.range(1, arr.length) .map(i -> arr[i]) .toArray(); } public static void main(String[] args) { int[] arr = {2, 3, 4, 8, 7, 1}; arr = removeFirstElement(arr); System.out.println(Arrays.toString(arr)); } } |
Output:
[3, 4, 8, 7, 1]
That’s all about removing the first element from an array in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)