How to remove last n number of elements from an array in java

In this article, we will learn how to remove last number of elements from an array in java .
Let’s understand what is an array?

An array in programming is a sequential collection of items of the same type stored in contiguous memory locations, allowing easy access to elements by calculating their positions relative to the start of the array.
it is a collection of similar type of data items at a contiguous memory location.

Remove last n elements from an array

Array-

The array [2,4,6,8] is an integer array containing four elements: 2, 4, 6, and 8. Arrays in Java are ordered collections of elements where each element is identified by its index.
The element 8 is highlighted to emphasize its position within the array.
CODE-

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Define an array named arr with values
        int arr[] = {2, 4, 6, 8};
        
        // Create a new array with size one less than the original array
        int newArr[] = new int[arr.length - 1];
        
        // Copy elements from the original array to the new array
        for (int i = 0; i < newArr.length; i++) {
            newArr[i] = arr[i];
        }
        
        // Print the original array and the new array 
        System.out.println("Original array : " + Arrays.toString(arr));
        System.out.println("Array after removing last element: " + Arrays.toString(newArr));
    }
}

OUTPUT-

Original array : [2, 4, 6, 8]
Array after removing last element: [2, 4, 6]

Key Points-

  • The code initializes an array arr with values { 2, 4, 6, 8}.
  • It creates a new array newArr with a length of 3 by excluding the last element (8) from arr.
  • Using a for loop, it copies elements from arr to newArr, effectively removing the last element.
  • Finally, it prints the contents of both arrays (arr and newArr) in a readable format using Arrays.toString().

 

you can also read about – how to convert stack to an array in java.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top