Last active
February 1, 2017 12:45
-
-
Save chankok/5d54b586d5bf805ab957fe96aaae36bc to your computer and use it in GitHub Desktop.
Check Even or Odd Number in Java http://www.chankok.com/java-check-even-or-odd-number/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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