w3resource

Java: Remove a specific element from an array

Java Array: Exercise-7 with Solution

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

Java Code Editor:

Previous: Write a Java program to find the index of an array element.
Next: Write a Java program to copy an array by iterating the array.

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.