This post will discuss how to remove the last element from an array in Java.

Since the size of an array cannot be changed in Java, you cannot remove any elements from it. However, you can create a new array, and then copy all the elements from the original array into the new array, except the last. There are several ways to do that:

1. Using Arrays.copyOf() method

The simplest solution is to remove the last element from an array is to use the Arrays.copyOf() method to copy the contents of the original array into a new array of one less size. The Arrays class provides several overloaded versions of the copyOf() method for all primitive types.

Download  Run Code

Output:

[5, 3, 4, 7, 6]

 
You can also use the Arrays.copyOfRange() method to copy the specified range of an array into a new array.

Download  Run Code

Output:

[5, 3, 4, 7, 6]

2. Using System.arraycopy() method

Another viable alternative is to leverage the System.arraycopy() method, which copies the specified range from the specified source array to the specified position in the destination array.

Download  Run Code

Output:

[5, 3, 4, 7, 6]

3. Using IntStream.range() method

In Java 8, you can use IntStream.range() to generate a sequential ordered IntStream between two specified indexes. Here’s complete usage of this method to remove the last element:

Download  Run Code

Output:

[5, 3, 4, 7, 6]

That’s all about removing the last element from an array in Java.