Array Java Programs

Delete Element of Array At Given Location

In this tutorial, we will learn to write a Java program that will delete an element of an array at a given index and output the updated array. Our program will delete the element at the position specified by the user from the given array.

For example

Case 1: If the given array is [1, 2, 3, 4] and the user enters 3 to delete the element at position 2, the output should be [1, 2, 4].

Case 2: If the given array is {9, 2, 4, 8} and the user enters 4 to remove the element at position 4, the output should be [9, 2, 4].

Delete Element of Array At Given Location in Java

import java.util.*;

public class ArrayExample {
	public static void main(String[] args) {
		int loc;
		Scanner sc = new Scanner(System.in);
		System.out.println("Java Program to delete element from given index");
		System.out.print("Enter the size of array: ");
		int size = sc.nextInt();
		int arr[] = new int[size];
		for (int i = 0; i < size; i++) {
			System.out.print("Please give value for index " + i + " : ");
			arr[i] = sc.nextInt();
		}
		System.out.println("Enter the index to delete element :");
		loc = sc.nextInt();
		if (loc <= size - 1) {
			for (int i = loc; i < size - 1; i++) {
				arr[i] = arr[i + 1];
			}
			size--;
		} else {
			System.out.print("index not available");
			System.exit(0);
		}
		System.out.println("Elements after deleting at index " + loc + " are:");
		for (int i = 0; i < size; i++) {
			System.out.print(arr[i] + "\t");
		}
	}
}

Explanation

From the input field [1, 2, 3, 4, 5], enter 2 to remove the element at position 2 in the array. Our program will iterate to position 2 in the array and remove the element with the statement arr[i] = arr[i+1]. Then the program will return the new updated array as output.

So after deleting the element at index 2, the output will be [1, 2, 4, 5]

Output

Java Program to delete element from given index
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 index to delete element :
2
Elements after deleting at index 2 are:
1	2	4	5	

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs