Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.chankok.operators;
public class CheckEvenOddNumberExample {
public static void main(String[] args) {
// Initial the integer array
int[] intArrays = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
/*
* Example 1: Check even or odd number using modulus operator (%)
*/
System.out.println("Example 1: Use modulus operator");
for (int number: intArrays) {
if (number % 2 == 0) {
// This is even number
System.out.println(number + " is even number");
} else {
// This is odd number
System.out.println(number + " is odd number");
}
}
// Print new line
System.out.println();
/*
* Example 2: Check even or odd number using bitwise AND operator (&)
*/
System.out.println("Example 2: Use bitwise AND operator");
for (int number: intArrays) {
if ((number & 1) == 0) {
// This is even number
System.out.println(number + " is even number");
} else {
// This is odd number
System.out.println(number + " is odd number");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment