Java Program to Remove Elements from the array

0
9
methods of Object

Here is a description of the process that the Java program to remove elements from an array follows:

  1. The program defines a method removeElement that takes an array and an index as input.
  2. The method checks if the index is valid (i.e., it is within the bounds of the array). If the index is invalid, the method throws an IllegalArgumentException.
  3. The method creates a new array with a length one less than the original array.
  4. The method copies elements from the original array to the new array, except for the element at the specified index. This is done using a loop and an if statement to skip the element at the index.
  5. The method returns the new array.
  6. The main method calls the removeElement method several times to remove elements from the array at different indices.
  7. The main method prints the array after each element has been removed.

I hope this helps! Let me know if you have any questions.

Here is a Java program that removes elements from an array:

import java.util.Arrays;

public class RemoveElements {
  public static void main(String[] args) {
    // Initialize an array
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    System.out.println("Original array: " + Arrays.toString(arr));

    // Remove the element at index 5
    arr = removeElement(arr, 5);
    System.out.println("Array after removing element at index 5: " + Arrays.toString(arr));

    // Remove the element at index 0
    arr = removeElement(arr, 0);
    System.out.println("Array after removing element at index 0: " + Arrays.toString(arr));

    // Remove the element at the last index
    arr = removeElement(arr, arr.length - 1);
    System.out.println("Array after removing element at the last index: " + Arrays.toString(arr));
  }

  public static int[] removeElement(int[] arr, int index) {
    // Check if the index is valid
    if (index < 0 || index >= arr.length) {
      throw new IllegalArgumentException("Invalid index: " + index);
    }

    // Create a new array with a length one less than the original array
    int[] newArr = new int[arr.length - 1];

    // Copy elements from the original array to the new array, except for the element at the specified index
    for (int i = 0, j = 0; i < arr.length; i++) {
      if (i != index) {
        newArr[j++] = arr[i];
      }
    }

    return newArr;
  }
}

This program defines a method removeElement that takes an array and an index as input, and returns a new array with the element at the specified index removed. The main method calls this method several times to remove elements from the array at different indices.

Output:

Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array after removing element at index 5: [1, 2, 3, 4, 5, 7, 8, 9]
Array after removing element at index 0: [2, 3, 4, 5, 7, 8, 9]
Array after removing element at the last index: [2, 3, 4, 5, 7, 8]

LEAVE A REPLY

Please enter your comment!
Please enter your name here