w3resource

Java: Remove all occurrences of a specified value in a given array, return the new length

Java Basic: Exercise-144 with Solution

Write a Java program to remove all occurrences of a specified value in a given array of integers. Return the updated array length.

Pictorial Presentation:

Java Basic Exercises: Remove all occurrences of a specified value in a given array of integers and return the new length of the array.

Sample Solution:

Java Code:

import java.util.*;
public  class Solution {
     /** 
     *@param nums: A list of integers
     *@param element: An integer
     *@return: The new length after remove
     */
  public static int removeElement(int[] nums, int elem) {
      int length = nums.length; 
      if(length==0) return 0; 
      int i=0; 
      for(int j=0; j<length; j++)
      {
        if(nums[j]!=elem)
        {
          nums[i]=nums[j];
          i++; 
        }
      }
      if(i<length) nums[i]='\0';
      return i; 
    }
    public static void main(String[] args) {
		int x = 6;
		int [] nums = {1,4,6,7,6,2};
		System.out.println("Original array: "+Arrays.toString(nums));
        System.out.println("The length of the new array is: " + removeElement(nums, x));
	}		
}

Sample Output:

Original array: [1, 4, 6, 7, 6, 2]
The length of the new array is: 4

Flowchart:

Flowchart: Java exercises: Remove all occurrences of a specified value in a given array of integers and return the new length of the array.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to merge two given sorted lists.
Next: Write a Java program to remove the nth element from the end of a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Handling Null Pointer Exception

Null pointer exception is a runtime exception that is thrown when an application is trying to use an object reference with a null value.

String fruit;
spellChecker(fruit);

Here a null reference variable is passed as an argument of a method.

positionLocator(null);

In the above code snippet, null is directly passed to a function. In both these instances, there is a high possibility of throwing the NullPointerException.

This exception can be fixed by using the if-else condition.

public class NullPointerExceptionExample{
    public static void main(String args[]){
        String fruit = "apple";
        positionLocator(null);
}//Using an if-else condition
    static void positionLocator(String fruit){
        if(fruit != null){
           System.out.println("Second character: "+fruit.charAt(0));
        }
        else {
           System.out.println("NullPointerException thrown");
        }
    }}

Ref: https://bit.ly/3mi39Nr

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook