Misc-Java-Examples

How to check if a number is even or odd

Posted On
Posted By admin

This blog post demonstrates how you can check if a number is even or odd via Java.

 

Consider the following code snippet:


public class EvenOddDemo {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your input:");
int num = scanner.nextInt();

if(num % 2 == 0)
System.out.println("The input number "+num+" is even");
else
System.out.println("The input number "+num+" is odd");
scanner.close();

}

}

 

This code first reads an input number using the Scanner class. It then uses the % operator. The % operator returns the remainder of division. So the code checks if the remainder obtained after dividing by 2 is 0. If so, the number is odd, otherwise the number is even.

So if you run the code with input as 4, the following output is printed:

Enter your input:
4
The input number 4 is even

 

If you run the code with input as 7, the following output is printed:

Enter your input:
7
The input number 7 is odd
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my Java course here

Also, if you'd like to test your Java knowledge, do check out my practice tests course here


If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment