Removing odd numbers from an array involves iterating through the elements, identifying odd numbers, and creating a new array that excludes them. In this post, we will explore two examples of removing odd numbers from an array in Java: one using a traditional array approach and the other leveraging an ArrayList
for dynamic resizing.
Example-1: Without Using ArrayList
This program example creates a new array to store only even numbers by manually counting and filtering elements from the original array.
package com.javacodepoint.array;
public class RemoveOddNumbersExample1 {
public static void main(String[] args) {
int[] arr = { 10, 15, 20, 25, 30, 35, 40 };
// Count even numbers
int evenCount = 0;
for (int num : arr) {
if (num % 2 == 0) {
evenCount++;
}
}
// Create a new array for even numbers
int[] evenArray = new int[evenCount];
int index = 0;
// Populate the new array with even numbers
for (int num : arr) {
if (num % 2 == 0) {
evenArray[index++] = num;
}
}
// Print the new array
System.out.println("Array after removing odd numbers:");
for (int num : evenArray) {
System.out.print(num + " ");
}
}
}
OUTPUT:
Array after removing odd numbers:
10 20 30 40
Example-2: Using ArrayList
This program example dynamically filters even numbers into an ArrayList
, which is later converted back to an array for the final output.
package com.javacodepoint.array;
import java.util.ArrayList;
public class RemoveOddNumbersExample2 {
public static void main(String[] args) {
int[] arr = { 10, 15, 20, 25, 30, 35, 40 };
ArrayList<Integer> evenList = new ArrayList<>();
// Add only even numbers to the list
for (int num : arr) {
if (num % 2 == 0) {
evenList.add(num);
}
}
// Convert ArrayList to array
int[] evenArray = new int[evenList.size()];
for (int i = 0; i < evenList.size(); i++) {
evenArray[i] = evenList.get(i);
}
// Print the new array
System.out.println("Array after removing odd numbers:");
for (int num : evenArray) {
System.out.print(num + " ");
}
}
}
OUTPUT:
Array after removing odd numbers:
10 20 30 40
Read also: Copy an Array | Count Repeated Elements in an Array | Searching in Java with Examples