Tutorial

How to Remove Array Elements in Java

Updated on May 2, 2025
authorauthor

By Jayant Verma and Anish Singh Walia

How to Remove Array Elements in Java

Introduction

In Java, arrays are a fundamental data structure that allows us to store a collection of elements of the same data type. When we declare an array, we specify its data type and size, which is used by the Java Virtual Machine (JVM) to allocate the necessary memory for the array elements. This fixed-size nature of arrays is both a strength and a weakness. On one hand, it allows for efficient memory allocation and access. On the other hand, it makes it challenging to dynamically modify the array, such as removing elements, as the size of the array cannot be changed once it is created. Unlike some other programming languages, Java does not provide a built-in method to remove elements from an array.

This limitation requires developers to implement their own methods to achieve array element removal, which can be cumbersome and error-prone.

1. Removing an element from Array using for loop

This method requires the creation of a new array. We can use for loop to populate the new array without the element we want to remove.

package com.journaldev.java;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5};
        int[] arr_new = new int[arr.length-1];
        int j=3;
        for(int i=0, k=0;i<arr.length;i++){
            if(i!=j){
                arr_new[k]=arr[i];
                k++;
            }
        }
        System.out.println("Before deletion :" + Arrays.toString(arr));
        System.out.println("After deletion :" + Arrays.toString(arr_new));

    }
}

Arr Delete

The code removes the element at index 3. This method simply copies all the elements except the one at index 3 to a new array.

2. Deleting an array element by its value

Unlike the previous case, this code will delete the element based on its value. This will not work with duplicates since the size of the array after deletion has to be known.

package com.journaldev.java;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5};
        int[] arr_new = new int[arr.length-1];
        int j=3;
        for(int i=0, k=0;i<arr.length;i++){
            if(arr[i]!=j){
                arr_new[k]=arr[i];
                k++;
            }
        }
        System.out.println("Before deletion :" + Arrays.toString(arr));
        System.out.println("After deletion :" + Arrays.toString(arr_new));

    }
}

Arr Delete based on value

The only difference between this and the previous case is arr[i]!=j in the if condition in place of i!=j.

3. Deleting element by its value when the array contains duplicates

Performing deletion based on the value in case of duplicates requires using ArrayList. Since ArrayList doesn’t require the size to be now in advance, it allows us to expand dynamically.

package com.journaldev.java;

import java.util.ArrayList;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] arr = new int[]{1,3,3,4,5};
        ArrayList<Integer> arr_new = new ArrayList<>();
        int j=3;
        for(int i=0;i<arr.length;i++){
            if(arr[i]!=j){
                arr_new.add(arr[i]);

            }
        }
        System.out.println("Before deletion :" + Arrays.toString(arr));
        System.out.println("After deletion :" +arr_new);

    }
}

array-deletion-duplicates

4. Shifting elements in the same array

This method involves shifting the elements in the same array. Shifting of elements replaces the element to be deleted by the element at the next index.

package com.journaldev.java;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
        int[] arr = new int[]{1,3,3,4,5};
        int j=3;
        System.out.println("Before deletion :" + Arrays.toString(arr));
        int count =0;
        for(int i = 0; i < arr.length; i++){
            if(arr[i] == j){
                count++;

                // shifting elements
                for(int k = i; k < arr.length - 1; k++){
                    arr[k] = arr[k+1];
                }
                i--;
               // break;
            }
        }

        System.out.print("After Deletion :" );
        for(int i = 0; i < arr.length-count; i++){
            System.out.print(" " + arr[i]);
        }
        System.out.println();
        System.out.println("Whole array :" + Arrays.toString(arr));

    }
}

Count variable indicates the number of elements deleted. This variable is essential to keep a track of index till which the array should be printed. This method takes care of duplicates as well.

Shifting Elements In Array

5. Deleting elements from ArrayList

ArrayList is backed by arrays. The deletion of an element in the ArrayList is straight forward. It requires one simple call to an inbuilt function.

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
        int[] arr = new int[]{1,3,3,4,5};
        ArrayList<Integer> arr_new = new ArrayList<Integer>();
        for (int i : arr)
        {
            arr_new.add(i);
        }
        arr_new.remove(3);
        System.out.println("Before deletion :" + Arrays.toString(arr));
        System.out.println("After Deletion:" + arr_new);
    }
}

A call to the remove(i) function removes the element at index i. Deletion in ArrayLists is relatively easier as compared to Arrays.

ArrayList Deletion

Manual shifting of elements

This approach involves manually shifting elements in the array to remove a specific element. It requires iterating through the array, finding the element to be removed, and then shifting all elements after it one position to the left. This method can be time-consuming for large arrays and is not suitable for arrays with a large number of elements to be removed.

Here is an example of how manual shifting of elements can be implemented in Java:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int removeIndex = 2;
        for (int i = removeIndex; i < arr.length - 1; i++) {
            arr[i] = arr[i + 1];
        }
        System.out.println("After removal: ");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Using System.arraycopy()

System.arraycopy() is a method in Java that can be used to copy elements from one array to another. It can be used to remove an element from an array by copying all elements before the element to be removed, and then copying all elements after the element to be removed, starting from the position of the element to be removed. This method is more efficient than manual shifting but still requires creating a new array.

Here is an example of how System.arraycopy() can be used to remove an element from an array in Java:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int removeIndex = 2;
        int[] newArr = new int[arr.length - 1];
        System.arraycopy(arr, 0, newArr, 0, removeIndex);
        System.arraycopy(arr, removeIndex + 1, newArr, removeIndex, arr.length - removeIndex - 1);
        System.out.println("After removal: ");
        for (int i = 0; i < newArr.length; i++) {
            System.out.print(newArr[i] + " ");
        }
    }
}

Converting array to ArrayList, removing, then converting back

This approach involves converting the array to an ArrayList, removing the element from the ArrayList, and then converting the ArrayList back to an array. ArrayLists provide a built-in method to remove elements, making this process easier. However, this method involves additional steps of conversion, which can be time-consuming for large arrays.

Here is an example of how an array can be converted to an ArrayList, an element can be removed, and then the ArrayList can be converted back to an array in Java:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        ArrayList<Integer> list = new ArrayList<>();
        for (int i : arr) {
            list.add(i);
        }
        list.remove(2);
        int[] newArr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            newArr[i] = list.get(i);
        }
        System.out.println("After removal: ");
        for (int i = 0; i < newArr.length; i++) {
            System.out.print(newArr[i] + " ");
        }
    }
}

Practical Use Cases

1. Removing invalid entries from user input arrays

When processing user input, it’s common to encounter invalid or erroneous data. Removing these entries from an array ensures that only valid data is processed, leading to more accurate results. For example, in a survey application, you might want to remove any responses that are outside a certain range or contain invalid characters.

Here’s an example of how you might implement this in Java:

public class Main {
    public static void main(String[] args) {
        int[] userResponses = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] validResponses = removeInvalidResponses(userResponses, 1, 10);
        System.out.println("Valid responses: ");
        for (int response : validResponses) {
            System.out.print(response + " ");
        }
    }

    public static int[] removeInvalidResponses(int[] responses, int min, int max) {
        int validCount = 0;
        for (int response : responses) {
            if (response >= min && response <= max) {
                validCount++;
            }
        }
        int[] validResponses = new int[validCount];
        int j = 0;
        for (int response : responses) {
            if (response >= min && response <= max) {
                validResponses[j] = response;
                j++;
            }
        }
        return validResponses;
    }
}

2. Cleaning up data before processing

Data cleaning is an essential step in data preprocessing. It involves removing or correcting inaccurate, incomplete, or irrelevant parts of the data to improve its quality. In the context of arrays, this might mean removing duplicates, handling missing values, or converting data types. For instance, in a financial application, you might need to remove any duplicate transactions or convert all dates to a standard format.

Here’s an example of how you might remove duplicates from an array in Java:

public class Main {
    public static void main(String[] args) {
        int[] transactions = {1, 2, 3, 4, 5, 2, 3, 6, 7, 8};
        int[] uniqueTransactions = removeDuplicates(transactions);
        System.out.println("Unique transactions: ");
        for (int transaction : uniqueTransactions) {
            System.out.print(transaction + " ");
        }
    }

    public static int[] removeDuplicates(int[] transactions) {
        boolean[] seen = new boolean[transactions.length];
        int uniqueCount = 0;
        for (int transaction : transactions) {
            boolean found = false;
            for (int i = 0; i < uniqueCount; i++) {
                if (transactions[i] == transaction) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                transactions[uniqueCount] = transaction;
                uniqueCount++;
            }
        }
        int[] uniqueTransactions = new int[uniqueCount];
        System.arraycopy(transactions, 0, uniqueTransactions, 0, uniqueCount);
        return uniqueTransactions;
    }
}

3. Building new arrays with filtered content

Filtering arrays is a common operation in many applications. It involves creating a new array that includes only elements that meet certain criteria. This is particularly useful when working with large datasets where you need to focus on a specific subset of the data. For example, in an e-commerce application, you might want to filter products based on their categories or prices.

Here’s an example of how you might filter products by category in Java:

public class Main {
    public static void main(String[] args) {
        Product[] products = {
            new Product("Electronics", 100),
            new Product("Electronics", 200),
            new Product("Clothing", 50),
            new Product("Clothing", 75),
            new Product("Electronics", 300),
            new Product("Home", 150),
            new Product("Home", 250)
        };
        Product[] filteredProducts = filterByCategory(products, "Electronics");
        System.out.println("Filtered products by category: ");
        for (Product product : filteredProducts) {
            System.out.println(product.toString());
        }
    }

    public static Product[] filterByCategory(Product[] products, String category) {
        int filteredCount = 0;
        for (Product product : products) {
            if (product.getCategory().equals(category)) {
                filteredCount++;
            }
        }
        Product[] filteredProducts = new Product[filteredCount];
        int j = 0;
        for (Product product : products) {
            if (product.getCategory().equals(category)) {
                filteredProducts[j] = product;
                j++;
            }
        }
        return filteredProducts;
    }
}

class Product {
    private String category;
    private int price;

    public Product(String category, int price) {
        this.category = category;
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    @Override
    public String toString() {
        return "Category: " + category + ", Price: " + price;
    }
}

Common Errors and Debugging

1. ArrayIndexOutOfBoundsException

This exception occurs when you try to access an array element using an index that is outside the bounds of the array. This can happen when you’re iterating over an array and mistakenly access an element at an index that doesn’t exist. To avoid this, ensure that your loop conditions correctly check the array bounds.

Example Code Snippet:

int[] arr = new int[5]; // Array with size 5
for (int i = 0; i <= arr.length; i++) { // Incorrect loop condition
    System.out.println(arr[i]); // This will throw ArrayIndexOutOfBoundsException
}
// Corrected loop condition
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

### 2. Forgetting to update array length or ignoring that arrays are fixed-size

In Java, arrays have a fixed size that is determined at the time of creation. If you're dynamically adding or removing elements from an array, you need to update the array size accordingly. Failing to do so can lead to errors or unexpected behavior. For example, if you're removing elements from an array, you should update the array length to reflect the new size.

**Example Code Snippet:**
```java
int[] arr = new int[5]; // Array with size 5
// Removing an element from the array without updating the size
arr[0] = 0; // Assuming this is the operation to remove the element
// The array size remains 5, but the first element is now effectively removed
// To correctly update the array size, you would need to create a new array with the updated size
int[] updatedArr = new int[arr.length - 1];
System.arraycopy(arr, 1, updatedArr, 0, arr.length - 1); // Copying elements starting from index 1 to the new array

3. Misuse of System.arraycopy() indices

System.arraycopy() is a powerful method for copying elements from one array to another. However, it requires careful attention to the indices used. If the indices are incorrect, you might end up copying the wrong elements or causing an ArrayIndexOutOfBoundsException. Always double-check the indices you’re using with System.arraycopy().

Example Code Snippet:

int[] sourceArr = {1, 2, 3, 4, 5};
int[] destArr = new int[3]; // Destination array with size 3
// Incorrect use of System.arraycopy()
System.arraycopy(sourceArr, 0, destArr, 0, sourceArr.length); // This will throw ArrayIndexOutOfBoundsException
// Correct use of System.arraycopy()
System.arraycopy(sourceArr, 0, destArr, 0, destArr.length); // Copying elements within the bounds of the destination array

FAQs

1. Can you remove an element from an array in Java?

Yes, you can remove an element from an array in Java. However, it’s important to note that arrays are fixed-size in Java, so you can’t directly remove elements from an array. Instead, you need to create a new array with the desired size and copy the elements from the original array to the new array, effectively removing the element.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int[] newArray = new int[originalArray.length - 1];
System.arraycopy(originalArray, 0, newArray, 0, originalArray.length - 1);
// newArray now contains elements {1, 2, 3, 4}, effectively removing the last element.

2. How do you remove an element from an array by index in Java?

To remove an element from an array by index in Java, you need to create a new array with the desired size, copy elements before the index to be removed to the new array, and then copy elements after the index to be removed to the new array, starting from the position of the element to be removed.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int removeIndex = 2; // Index of the element to be removed
int[] newArray = new int[originalArray.length - 1];
System.arraycopy(originalArray, 0, newArray, 0, removeIndex);
System.arraycopy(originalArray, removeIndex + 1, newArray, removeIndex, originalArray.length - removeIndex - 1);
// newArray now contains elements {1, 2, 4, 5}, effectively removing the element at index 2.

3. Why can’t you directly remove elements from arrays in Java?

You can’t directly remove elements from arrays in Java because arrays are fixed-size, meaning their size is determined at the time of creation and cannot be changed later. This is a fundamental property of arrays in Java, which makes it necessary to use workarounds like creating a new array to effectively remove elements.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int removeIndex = 2; // Index of the element to be removed
int[] newArray = new int[originalArray.length - 1];

4. What is the best way to delete elements from an array in Java?

The best way to delete elements from an array in Java depends on the specific requirements and constraints of your application. However, in general, using System.arraycopy() is a more efficient approach than manual shifting of elements, especially for large arrays. Converting the array to an ArrayList, removing the element, and then converting back to an array is another option, but it involves additional steps of conversion.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int removeIndex = 2; // Index of the element to be removed
int[] newArray = new int[originalArray.length - 1];
System.arraycopy(originalArray, 0, newArray, 0, removeIndex);
System.arraycopy(originalArray, removeIndex + 1, newArray, removeIndex, originalArray.length - removeIndex - 1);
// newArray now contains elements {1, 2, 4, 5}, effectively removing the element at index 2.

5. How do you remove multiple elements from a Java array?

To remove multiple elements from a Java array, you can use a combination of the approaches mentioned earlier. For example, you can create a new array and copy elements to it, excluding the elements to be removed. Alternatively, you can convert the array to an ArrayList, remove the elements, and then convert back to an array.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int[] indicesToRemove = {1, 3}; // Indices of elements to be removed
int[] newArray = new int[originalArray.length - indicesToRemove.length];
int j = 0;
for (int i = 0; i < originalArray.length; i++) {
    boolean found = false;
    for (int index : indicesToRemove) {
        if (i == index) {
            found = true;
            break;
        }
    }
    if (!found) {
        newArray[j] = originalArray[i];
        j++;
    }
}
// newArray now contains elements {1, 3, 5}, effectively removing elements at indices 1 and 3.

6. How do I avoid shifting elements manually in Java?

To avoid shifting elements manually in Java, you can use System.arraycopy() to copy elements from the original array to a new array, effectively removing the element without manual shifting. This approach is more efficient and less error-prone than manual shifting, especially for large arrays.

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int removeIndex = 2; // Index of the element to be removed
int[] newArray = new int[originalArray.length - 1];
System.arraycopy(originalArray, 0, newArray, 0, removeIndex);
System.arraycopy(originalArray, removeIndex + 1, newArray, removeIndex, originalArray.length - removeIndex - 1);
// newArray now contains elements {1, 2, 4, 5}, effectively removing the element at index 2.

Conclusion

In this tutorial, we explored various methods for removing elements from arrays in Java, including using for loops, System.arraycopy(), and converting to an ArrayList. We also highlighted the advantages of using ArrayLists for frequent element deletion or addition due to their dynamic nature and built-in functions. For further learning, consider exploring the following tutorials:

These tutorials will provide you with a deeper understanding of working with lists and arrays in Java, including how to effectively manage and manipulate their elements.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 3, 2021

I was deleting an array element by shifting , similar to what you have done in method 4. Came here to see if I could do something to get rid of the duplicate elements that remain at the end of the array. Wanted to do this without copying to new array.

- Meena

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.