In this tutorial, we will learn to write a Java program to delete a specified element of an array and print the updated array. Our program will delete the specified element (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}.
Delete a Specified Element of Array in Java
import java.util.*;
public class ArrayExample {
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]);
}
}
}
Explanation
For the input array [1, 2, 4, 2, 6], and the element to be deleted is 2 from the array. Our program first traverses the array element to find 2. Once 2 is found, it is removed by moving all elements (that come after 2) one to the left. So after we delete 2, our array becomes [1,4,6]
Output
Java Program to delete given 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
Enter the element to delete :2
Rest elements of array after deleting 2 are :
1
3
4
5