Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Java Program to Check Even or Odd Number

    This Java example code demonstrates a simple Java program that checks whether a given number is an even or odd number and prints the output to the screen.

    Program:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
    
            Scanner reader = new Scanner(System.in);
    
            System.out.print("Enter a number: ");
            int num = reader.nextInt();
    
            if(num%2 == 0){
                System.out.println(num + " is even");
            }else{
                System.out.println(num + " is odd");
            }
        }
    }

    Program Output:

    Enter a number: 8
    8 is even

    If a number is evenly divisible by 2 without any remainder, then it is an even number; Otherwise, it is an odd number. The modulo operator % is used to check it in such a way as num%2 == 0.

    In the calculation part of the program, the given number is evenly divisible by 2 without remainder, so it is an even number.

    The above program can also be written using a ternary operator such as:

    Java Program to Check Even or Odd Number Using Ternary Operator

    Program:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
    
            Scanner reader = new Scanner(System.in);
    
            System.out.print("Enter a number: ");
            int num = reader.nextInt();
    
            String evenOdd = (num % 2 == 0) ? "even" : "odd";
            System.out.println(num + " is " + evenOdd);
        }
    }

    Program Output:

    Enter a number: 9
    9 is odd
    


    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.