OneBite.Dev - Coding blog in a bite size

remove a specific element from an array in java

Code snippet on how to remove a specific element from an array in java

  int removeElement(int[] arr, int index) {
    if (arr == null || index < 0 || index >= arr.length) {
        return -1;
    }
    int element = arr[index];
    for (int i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    return element;
}

This code removes a specific element from an array by using its index. First, it checks if the array exists or if the index is outside the array’s boundaries. If either of these conditions is true, the code returns -1. Otherwise, it stores the value of the element to be removed in a separate variable and then starting from the element at the given index, it moves all the elements after it up by one. Lastly, it the element’s value is returned.

java