Java program to delete specified integer from an array

Let’s learn java program to delete specified integer from an array.

Java program to delete specified integer from an array

Delete specified integer from an array in java is one of the common interview question.

java program to delete specified integer from an array

In the below java program first user enters number of integers of an array using nextInt() method of Scanner class. Then this number of integers of an array will be the size of the array.

Now user enters all the integers. Using for loop all the integers are stored in the array. In the next step user enters the integer to delete from array.

For this we have to first find location of element and then shift positions of all the elements one by one using if else and for loop.

java program to delete specified integer from an array

If the integer is found, delete specified integer and finally print the updated array. Here’s the program to delete specified integer from an array.

import java.util.Scanner;
public class DeleteSpecifiedInteger
{
   public static void main(String[] args)
   {
      int num, n, temp = 1, place = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of integers: ");
      num = sc.nextInt();
      int[] arrNum = new int[num];
      System.out.println("Please enter all the integers: ");
      for(int a = 0; a < num; a++)
      {
         arrNum[a] = sc.nextInt();
      }
      System.out.println("Enter the integer you want to delete: ");
      n = sc.nextInt();
      for(int a = 0; a < num; a++)
      {
         if(arrNum[a] == n)
         {
            temp = 1;
            place = a;
            break;
         }
         else
         {
            temp = 0;
         }
      }
      if(temp == 1)
      {
         for(int a = place + 1; a < num; a++)
         {
            arrNum[a - 1] = arrNum[a];
         }
         System.out.println("After deleting integer: ");
         for(int a = 0; a < num - 2; a++)
         {
            System.out.print(arrNum[a] + ",");
         }
         System.out.print(arrNum[num - 2]);
      }
      else
      {
         System.out.println("Integer not found!!");
      }
      sc.close();
   }
}

Output:

Please enter number of integers : 5
Please enter all the integers :
2
8
4
9
7
Enter the integer you want to delete : 9
After deleting integer : 2,8,4,7

Output:

Please enter number of integers : 5
Please enter all the integers :
3
5
9
4
2
Enter the integer you want to delete : 1
Integer not found!!


Meanwhile we can also remove integer from arraylist java.