w3resource

Java: Remove a specific element from an array


7. Remove specific element from array

Write a Java program to remove a specific element from an array.

Pictorial Presentation:

Java Array Exercises: Remove a specific element from an array


Sample Solution:

Java Code:

// Import the Arrays class from the java.util package.
import java.util.Arrays;

// Define a class named Exercise7.
public class Exercise7 {
 
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize an integer array 'my_array'.
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
   
        // Print the original array using Arrays.toString() method.
        System.out.println("Original Array : " + Arrays.toString(my_array));     
   
        // Define the index of the element to be removed (second element, index 1, value 14).
        int removeIndex = 1;

        // Loop to remove the element at the specified index.
        for (int i = removeIndex; i < my_array.length - 1; i++) {
            my_array[i] = my_array[i + 1];
        }
        
        // Print the modified array after removing the second element.
        System.out.println("After removing the second element: " + Arrays.toString(my_array));
    }
} 

Sample Output:

Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]                                                     
After removing the second element: [25, 56, 15, 36, 56, 77, 18, 29, 49, 49] 

Flowchart:

Flowchart: Java exercises: Remove a specific element from an array


For more Practice: Solve these Related Problems:

  • Write a Java program to remove all occurrences of a given value from an array.
  • Write a Java program to remove an element from an array without shifting the elements.
  • Write a Java program to remove every second element from an array.
  • Write a Java program to remove elements that are greater than a specified threshold.

Go to:


PREV : Find index of an element in array.
NEXT : Copy array using iteration.

Java Code Editor:

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.