Languages
[Edit]
EN

Java - check if number is odd or even

7 points
Created by:
Marcin
2462

If a number is divisible by two then it is even, otherwise, it is odd.
To find reminder in java we use modulo operator %.

Even numbers always end with a digit of 0, 2, 4, 6 or 8
Odd  numbers always end with a digit of 1, 3, 5, 7 or 9

Examples of even numbers:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26

Examples of odd numbers:
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27

public class JavaCheckIfNumberIsOddOrEven {

    public static void oddOrEven(int no) {
        if (no % 2 == 0) {
            System.out.println(no + " is even number");
        } else {
            System.out.println(no + " is odd number");
        }
    }

    public static void main(String[] args) {
        oddOrEven(4); // 4 is even number
        oddOrEven(5); // 5 is odd number
    }
}

Output:

4 is even number
5 is odd number

Reference:

Wiki - Parity
Modulo in java - syntax, how to use it with examples

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.