In this tutorial, we will learn writing Java program to delete a given element of an array from the end and print the array. Our program will delete the element from end (which is specified by the user) of the given array.
For example
Case 1: If the given array is {1, 2, 3, 4}.
Then output should be {1, 2, 3}.
Case 2: If the given array is {9, 2, 4, 8.
Then output should be {9, 2, 4}.
Java Program to Delete Element at End of Array
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.print(arr[i]+" ");
}
}
}
Output
Java Program to delete last element from Array
Enter the size of array: 5
Please give value for index 0 : 4
Please give value for index 1 : 3
Please give value for index 2 : 1
Please give value for index 3 : 6
Please give value for index 4 : 3
After deleting last element 3
4 3 1 6
What did you think?