Java – Remove First Element of Array

To remove first element of an Array in Java, create a new array with the size one less than the original array size, and copy the elements of original array, from index=1, to new array.

Or, we can also use Arrays.copyOfRange() function to create a new array without the first element.

Examples

In the following example, we take an integer array and create a new array with the first element removed from the original array.

In this program, we define a function removeFirstElement(int[] arr) that returns a new array with the first element removed from the given array arr.

Main.java

</>
Copy
public class Main {

    public static int[] removeFirstElement(int[] arr) {
        int newArr[] = new int[arr.length - 1];
        for (int i = 1; i < arr.length; i++) {
            newArr[i-1] = arr[i];
        }
        return newArr;
    }

    public static void main(String[] args) {
        int arr[] = {2, 4, 6, 8};
        
        int newArr[] = removeFirstElement(arr);

        System.out.println("Original  : " + Arrays.toString(arr));
        System.out.println("New Array : " + Arrays.toString(newArr));
    }

}

Output

Original  : [2, 4, 6, 8]
New Array : [4, 6, 8]

Based on the datatype of the array, we may modify the removeFirstElement() function, or define a new function that overloads this removeFirstElement() function.

In the following example, we create a new array with the first element removed from the original array using Array.copyOfRange() method.

Main.java

</>
Copy
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr[] = {2, 4, 6, 8};
        
        int newArr[] = Arrays.copyOfRange(arr, 1, arr.length);

        System.out.println("Original  : " + Arrays.toString(arr));
        System.out.println("New Array : " + Arrays.toString(newArr));
    }
}

Output

Original  : [2, 4, 6, 8]
New Array : [4, 6, 8]

Conclusion

In this Java Tutorial, we learned how to remove the first element of given array with examples.