Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

How to check if Number is Odd or Even in Java?

How to check if Number is Odd or Even in Java?

Here is a very simple Java example which tells you if given number is Even or Odd.

Java Program to check Even or Odd number. Even odd program in Java.

An even number is a number that can be divided into two equal groups. An odd number is a number that cannot be divided into two equal groups. One is the first odd positive number but it does not leave a remainder 1.

Another definition: Any integer that can be divided exactly by 2 is an even number.

Here is a Java program to check if given number is Odd or Even?

Create class CrunchifyCheckOddEven.java

package crunchify.com.java.tutorials;

import java.util.Scanner;

/**
 * @author Crunchify.com
 * How to check if Number is Odd or Even in Java?
 */

public class CrunchifyCheckOddEven {
        
        public static void main(String[] args) {
                int crunchifyNumber;
                crunchifyPrintResult("Let's check it out. Please enter integer number:");
                
                Scanner crunchifyInput = new Scanner(System.in);
                
                // Scans the next token of the input as an int.
                //An invocation of this method of the form nextInt() behaves in
                // exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
                crunchifyNumber = crunchifyInput.nextInt();
                
                /* An even number is a number that can be divided into two equal groups.
                An odd number is a number that cannot be divided into two equal groups. */
                if (crunchifyNumber % 2 == 0)
                        crunchifyPrintResult("Entered number " + crunchifyNumber + " is even");
                else
                        crunchifyPrintResult("Entered number " + crunchifyNumber + " is odd");
        }
        
        // Simple Print result method to printout console result
        private static void crunchifyPrintResult(String s) {
                System.out.println(s);
        }
        
}

Let’s run it.

Just run above program in Eclipse console or in IntelliJ IDEA and you will see some results like this.

Let's check it out. Please enter integer number:
33
Entered number 33 is odd

Process finished with exit code 0
Let's check it out. Please enter integer number:
32
Entered number 32 is even

Process finished with exit code 0

Let us know if you face any Java Exception while running this program.

The post How to check if Number is Odd or Even in Java? appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires