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:
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/array/java-array-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics