Java – Remove Last Element of Array
To remove the last element of an Array in Java, call Arrays.copyOf() method and pass the array and new size as arguments. The new size must be one less than the size of original array.
Examples
In the following example, we take an integer array and create a new array with the last element removed from the original array using Arrays.copyOf() 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.copyOf(arr, arr.length - 1);
System.out.println("Original : " + Arrays.toString(arr));
System.out.println("New Array : " + Arrays.toString(newArr));
}
}
Output
Original : [2, 4, 6, 8]
New Array : [2, 4, 6]
Conclusion
In this Java Tutorial, we learned how to remove the last element of given array with examples.