Array Java Programs

Delete Element at End of Array

In this tutorial, we will learn to write a Java program to delete a specific element of an array from the end and print the array. Our program will delete the element from the end (specified by the user) of the given array.

For example

Case 1: If the given array is {1, 2, 3, 4}, then the output should be {1, 2, 3}.

Case 2: If the given array is {9, 2, 4, 8}, then the output should be {9, 2, 4}.

Delete Element at End of Array in Java

import java.util.*;

public class Main {
	public static void main(String[] args) {
		int lastElement;
		Scanner sc = new Scanner(System.in);
		System.out.println("Java Program to delete last element from Array");
		System.out.print("Enter the size of array: ");
		int size = sc.nextInt();
		int arr[] = new int[size];
		for (int i = 0; i < size; i++) {
			System.out.print("Please give value for index " + i + " : ");
			arr[i] = sc.nextInt();
		}
		lastElement = arr[size - 1];
		System.out.println("After deleting last element " + lastElement);
		for (int i = 0; i < size - 1; i++) {
			System.out.println(arr[i]);
		}
	}
}

Explanation

For the input field {1, 2, 3, 4, 5}. The user enters the element 5 to be removed from the list and outputs the elements of the array except the last element of the array.

Output

Java Program to delete last element from Array
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
After deleting last element 5
1
2
3
4

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs