In this tutorial, We will learn writing java program to delete a given element of an Array and print the updated Array. Our program will delete the given element (which is specified by the user) from the array.
For Example
Case 1: if the given array is {1, 2, 3, 4} and the user gives input 3 to remove.
The output should be {1, 2, 4}.
Case 2: if the given array is {9, 2, 4, 8} and the user gives input 4 to remove.
The output should be {9, 2, 8}.
Java Program to Delete a given Element of Array
import java.util.*;
public class Main
{
public static void main(String[] args) {
int temp, value;
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to delete given element from Array");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
temp=size;
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
System.out.print("Enter the element to delete :");
value=sc.nextInt();
for(int i=0; i<size; i++)
{
if(arr[i]==value){
for(int j=i; j<size-1; j++){
arr[j] = arr[j+1];
}
size--;
i--; ;
}
}
if(temp==size){
System.out.println("No element found "+value+" in array ");
System.exit(0);
}
System.out.println("Rest elements of array after deleting "+value+" are :");
for(int i=0; i<size; i++)
{
System.out.println(arr[i]);
}
}
}
Output
Java Program to delete given 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 : 2
Please give value for index 3 : 5
Please give value for index 4 : 3
Enter the element to delete :3
Rest elements of array after deleting 3 are :
4
2
5
Explanation
For the input array [4,3,2,5,3], and element to be delete is 3 from the array. Our program first iterate through the array element to find 3, once 3 has been found it, it removes by shifting all elements (which comes after 2), to one left. So here after deleting 3 our array become [4,2,5]