Java Program to delete an element in an array


In this program, You will learn how to delete an element in an array in java.


List is: 2 3 5 7 9 11 13

Delete element is: 13

After delete list is: 2 3 5 7 9 11

Example: How to delete an element in an array in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, n, num, p = 0;
        int arr[] = new int[100];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter size of an array:");
        n = sc.nextInt();

        System.out.print("Enter array elements:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter element for delete:");
        num = sc.nextInt();

        for (i = 0; i < n; i++) {
            if (arr[i] == num) {
                arr[i] = arr[i + 1];
                p = 1;
            } else if (p > 0) {
                arr[i] = arr[i + 1];
            }
        }

        System.out.print("New Array list are:");
        for (i = 0; i < n - p; i++) {
            System.out.print(" " + arr[i]);
        }

    }
}

Output:

Enter size of an array:5
Enter array elements:10 20 30 40 50
Enter element for delete:30
New Array list are: 10 20 40 50