codescracker


java

Java Program to Delete Element from Array



« Previous Program Next Program »


Delete Element from Array

To delete any element from an array in Java programming, you have to first ask to the user to enter the size and elements of the array, now ask to enter the element/number which is to be delete. Now to delete that element from the array first you have to search that element to check whether that number is present in the array or not, if found then place the next element after the founded element to the back until the last as shown in the following program.

Java Programming Code to Delete Element from Array

Following Java Program ask to the user to enter array size, then ask to enter array elements, it will again ask to enter the element to be delete, to delete this element from the array, then display the new array on the screen:

/* Java Program Example - delete Element from Array */
	
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, i, del, count=0;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
	   
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Enter Element to be Delete : ");
       del = scan.nextInt();
       for(i=0; i<size; i++)
       {
           if(arr[i] == del)
           {
               for(int j=i; j<(size-1); j++)
               {
                   arr[j] = arr[j+1];
               }
               count++;
               break;
           }
       }
       if(count==0)
       {
           System.out.print("Element Not Found..!!");
       }
       else
       {
           System.out.print("Element Deleted Successfully..!!");
           System.out.print("\nNow the New Array is :\n");
           for(i=0; i<(size-1); i++)
           {
               System.out.print(arr[i]+ " ");
           }
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program delete element from array

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test