Delete an Element from an Array in Java

Write a program to allow the user to enter N integers into a one-dimensional array. The value of N is to be input by the user.

Then ask the user to enter the index from where he/she wants to delete an element. Perform the deletion and then display the resultant array.

import java.io.*;
class MyArray{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Array size: ");
        int size = Integer.parseInt(br.readLine());
        int a[] = new int[size];
        System.out.println("Enter array elements:");
        for(int i = 0; i < size; i++)
            a[i] = Integer.parseInt(br.readLine());
        System.out.print("Index to delete from: ");
        int index = Integer.parseInt(br.readLine());
        if(index < 0 || index >= size){
            System.out.println("Invalid index!");
            return;
        }
        if(index == size - 1)
            a[index] = 0;
        else{
            for(int i = index + 1; i < size; i++)
                a[i - 1] = a[i];
            a[size - 1] = 0;
        }
        System.out.println("Resultant array after deletion:");
        for(int i = 0; i < size; i++)
            System.out.print(a[i] + "\t");
        System.out.println();
    }
}

2 thoughts on “Delete an Element from an Array in Java”

  1. Sir,in the deletion of an element in array from a specified index in java ,the loop will run from 0 to size-1 or from 0 to size -2?

Leave a Reply

%d bloggers like this: