Define "remove".

Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;

for (int i = 0; i < myStringArray.length(); i++)
{
    if (myStringArray[i].equals(stringToRemove))
    {
        myStringArray[i] = null;
        break;
    }
}

or

myStringArray[indexOfStringToRemove] = null;

If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>

myArrayList.remove(stringToRemove); 

or

myArrayList.remove(indexOfStringToRemove);

Edit in response to OP's edit to his question and comment below

String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
Answer from Brian Roach on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java array › remove all elements from a string array in java
Remove All Elements From a String Array in Java | Baeldung
August 20, 2024 - That is to say, when an array has been initialized and assigned to a final variable, we cannot remove its elements to get an empty array (length=0). One approach to “removing” elements from an array is to set each element to null.
🌐
Quora
quora.com › How-does-one-remove-an-element-from-an-array-in-Java
How does one remove an element from an array in Java? - Quora
Answer (1 of 10): Removing an element from an array is a cumbersome effort if the order matters in your array. Otherwise, it is really easy. Let me explain both ways. Order of the elements does NOT matter Let’s assume your have a partially filled array [5, 9, 6, 8, 0, 0, 0] (0 means don’t ...
🌐
Software Testing Help
softwaretestinghelp.com › home › java › remove/delete an element from an array in java
Remove/Delete An Element From An Array In Java
April 1, 2025 - Learn Various Methods to Delete or Remove an element from an Array in Java such as Using another array, Using Java 8 Streams, Using ArrayList etc.
🌐
Coderanch
coderanch.com › t › 528600 › java › Remove-element-array-index
Remove an element from array by index (Beginning Java forum at Coderanch)
In particular I would recommend an ArrayList<String> -- if you check the documentation you'll find it has a method to remove a sub-list as you described. ... Assign the new array to the reference of the old array. ... If you need to remove elements, an array isn't a good choice.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-remove-array-elements
How to Remove Array Elements in Java | DigitalOcean
May 2, 2025 - 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(res
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-an-element-at-specific-index-from-an-array-in-java
Remove an Element at Specific Index from an Array in Java - GeeksforGeeks
July 11, 2025 - // Java program to remove an element ... main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; int in = 2; // Remove the element arr = remove(arr, in); System.out.println(Arrays.toString(arr)); } }...
🌐
Netjstech
netjstech.com › 2017 › 07 › how-to-remove-elements-from-array-java.html
How to Remove Elements From an Array Java Program | Tech Tutorials
When you remove an element from an array, you can fill the empty space with 0, space or null depending on whether it is a primitive array, string array or an Object array. Other alternative is to create a new array and copy the elements in that array. New array should have size of old array’s ...
🌐
Stack Overflow
stackoverflow.com › questions › 59348581 › how-can-i-remove-an-element-from-array-in-java
How can i remove an element from array in Java - Stack Overflow
For example, to remove an element at a particular index, you could do it like this: public static String[] remove(String[] array, int index) { String[] result = new String[array.length - 1]; System.arraycopy(array, 0, result, 0, index); ...
Top answer
1 of 5
5

You need 2 indices in the second loop, since you are iterating over two arrays (the input array and the output array) having different lengths.

Besides, newLength is a confusing name, since it doesn't contain the new length. It contains the difference between the input array length and the output array length. You can change its value to match its name.

int newLength = arr.length;
for(int i = 0; i < arr.length; i++)
{    
    if(arr[i].contains(toRemove))
    {
        newLength--;
    }
}
String[] result = new String[newLength];
int count = 0; // count tracks the current index of the output array
for(int i = 0; i < arr.length; i++) // i tracks the current index of the input array
{
    if(!arr[i].contains(toRemove)) {
        result[count] = arr[i]; 
        count++;
    }
}
return result;
2 of 5
0

There's the error that @Eran pointed out in your code, which can solve your problem. But I'm going to discuss another approach.

For now, you're first iterating over the entire array to find the number of occurrences to remove, and then, you're iterating over the array to remove them. Why don't you just iterate over the array, just to remove them. (I know, your first loop is helping you to determine the size of the output array, but you don't need that if you use some List like ArrayList etc.)

List<String> resultList = new ArrayList<String>();
for(int i = 0; i < arr.length; i++)
{
    if(!arr[i].contains(toRemove))
    {
        resultList.add(arr[i]);
    }
}

And you can return the resultList, but if you really need to return an array, you can convert the resultList to an array like this:

String [] resultArray = resultList.toArray(new String[resultList.size()]);

And then return this array. See this approach live here on ideone.

🌐
Stack Abuse
stackabuse.com › remove-element-from-an-array-in-java
Remove Element from an Array in Java
December 16, 2021 - Due to the nature of array's memory placement, it is simply impossible to remove the element directly. Instead, to "remove" any element, all subsequent elements need to be shifted backward by one place. This will create an illusion that a specific element was removed.
🌐
Java67
java67.com › 2012 › 12 › how-to-remove-element-from-array-in-java-example.html
How to Remove an Element from Array in Java with Example | Java67
How to remove a number from an Integer Array in Ja... How Binary Search Algorithm Works? Java Example wi... How to declare and Initialize two dimensional Arra... How to compare two Arrays in Java to check if they... How to Convert or Print Array to String in Java?
🌐
How to do in Java
howtodoinjava.com › home › java array › removing items from an array in java
Removing Items from an Array in Java
February 10, 2022 - Learn to remove the array items in Java by the index positions as well as the item values using ArrayUtils, Collections APIs and custom code.
🌐
Reddit
reddit.com › r/learnprogramming › having trouble with java arrays, removing an element then returning a new size of an array
r/learnprogramming on Reddit: Having trouble with java arrays, removing an element then returning a new size of an array
July 13, 2018 -

So guys i'm having trouble finding a solution for this question. I'm kinda frustrated that i didn't solve this kind of problem during my exam for employment.

Problem: The task is to provide an implementation for the given function. int[] removeElem(int[] array, value), the objective is to find if the array contains the given 'value' inside it. if found then remove the element from the array then return an array with a new size, else return original array.

So far this is what i got:

  public static void main(String[] args) {
  int[] myArray = {5,6,9,4};
  
  int[] newArray = removeElem(myArray,9);
  
  for(int i=0;i<newArray.length;i++){
      System.out.print(newArray[i] + " ");
  }

}

public static int[] removeElem(int[] array, int value){
    int[] tempArray = array;
    int newArrayLength = 0;
    int[] newArray;
    
    for(int index=0;index < tempArray.length; index++){
        if(tempArray[index] == value){
            tempArray[index] = -1;
            newArrayLength++;
        }
    }
    
    newArray = new int[tempArray.length - newArrayLength];
    for(int index=0;index < newArray.length; index++){
        if(tempArray[index] != -1){
            newArray[index] = tempArray[index];
        }
    }
    
    return newArray;
    
}

Unfortunately i can't get it right :/

Edit: Thank you! everyone for suggesting different solutions to this problem, I feel like I need to work more on my solutions and such :|.

Top answer
1 of 5
2
I’m on my phone so I’ll just explain what im thinking in pseudo code, but why don’t you just do something like: Create a new array of size n-1 where n is the size of the original array. Iterate over the old array in a for loop, adding each element to the new array. If the element at the ith position equals the element to remove, continue to the next iteration. Would that work? EDIT: I'm at my PC now so here's the code. I ended up doing it a little differently than I mentioned above. Note that it doesn't account for if the element appears multiple times in the array or when the element does not exist. public static void main(String []args) { int[] myArray = { 5,6,9,4 }; int[] newArray = removeElem(myArray, 9); for (int i = 0; i < newArray.length; i++) System.out.print(newArray[i] + " "); } public static int[] removeElem(int[] array, int value) { int index = -1; // First confirm the element to remove exists in the array for (int i = 0; i < array.length; i++) { // If it does, store its index if (array[i] == value) index = i; } // If element exists if (index != -1) { int[] newArray = new int[array.length - 1]; for (int i = 0; i < array.length; i ++) { if (i < index) newArray[i] = array[i]; else if (i > index) newArray[i - 1] = array[i]; } return newArray; } // Do some error handling for if the element does not exist else return array; } Output is: 5 6 4
2 of 5
2
newArray[index] = tempArray[index]; This is your problem. As you skip elements that are to be removed, the insertion index in newArray must no longer match the read index in tempArray, but you're using the same index for both. You need to use two indices, and only increment the newArray index when you insert an element, while incrementing the tempArray index every time. Also the whole thing would be better if you just used Lists or Streams, but maybe your interviewer didn't want that. It's really best to try to avoid using raw arrays in Java.
🌐
Baeldung
baeldung.com › home › java › java array › removing the first element of an array
Removing the First Element of an Array | Baeldung
April 22, 2025 - First of all, removing an element of an array isn’t technically possible in Java. To quote the official docs: “An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.” · This means as long as we’re working with an array directly, all we can do is create a new array of smaller size, which then doesn’t contain the first element.