
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Odd and Even Numbers from an Array in Java
Given an array of type Integer, write a Java program to find the odd and even numbers from that array. Those numbers which are completely divisible by 2 are called even numbers and if a number gives 1 as a remainder on dividing with 2 is known as odd number.
Printing Odd and Even Number from an Array
To print odd and even number from an array in Java, use the following ways ?
- Using for Loop
- Using stream API
Using for Loop
In this approach, use the for loop to iterate over the elements of the array and in this loop use a if block to check whether the given input number is odd or even.
Example
In this example, we are using for loop to print odd and even number from an array.
public class OddNumbersInAnArray { public static void main(String args[]){ int[] myArray = {23, 93, 56, 92, 39}; System.out.println("Even numbers in the given array are:: "); for (int i=0; i<myArray.length; i++){ if(myArray[i]%2 == 0){ System.out.println(myArray[i]); } } System.out.println("Odd numbers in the given array are:: "); for (int i=0; i<myArray.length; i++){ if(myArray[i]%2 != 0){ System.out.println(myArray[i]); } } } }
On running, this code will display the following result ?
Even numbers in the given array are:: 56 92 Odd numbers in the given array are:: 23 93 39
Using stream API
This is another approach to find odd and even numbers from an array. Here, we use the Java streams which is used to process a collection of objects. In this approach, the filter() method will separate the odd and even numbers from the specified array.
Example
The following example explains how to print odd and even number from an array with the help of stream API.
import java.util.Arrays; public class OddEvenInAnArray { public static void main(String[] args) { Integer[] myArray = {121, 25, 34, 14, 50, 62, 27}; System.out.println("Even numbers in the given array are::"); // filtering even numbers Arrays.stream(myArray) .filter(nums -> nums % 2 == 0) .forEach(System.out::println); // filtering odd numbers System.out.println("Odd numbers in the given array are::"); Arrays.stream(myArray) .filter(nums -> nums % 2 != 0) .forEach(System.out::println); } }
When you execute this code, it will show the following output ?
Even numbers in the given array are:: 34 14 50 62 Odd numbers in the given array are:: 121 25 27