Aug 1, 2024

Java Program to Check Given Number is Even or Odd

In this post, we are going to see two ways to print whether a given number is even or odd in Java. First one is using if-else statements, and another one without using if-else statements, using the ternary operator in Java. So, let's dive into the discussion of how to check whether a given number is even or odd.


Step by Step logic of the given Program:

  1. First Create a Scanner class object to accept input from user.
  2. Accept input from user and store that in variable called num.
  3. Use if-else statement and modulus (%) operator to check whether given number is even or odd and print it on the console.



Example 1: Java Program to Check whether a given number is even or odd using If-else statement

import java.util.Scanner;

public class EvenOddNumber
{
	public static void main(String[] args) {
	    //
	    Scanner sc = new Scanner(System.in);
	    
	    //Accept input from user
	    System.out.println("Enter a Number: ");
            int num = sc.nextInt();
        
            //Check given number is even or odd
            if(num % 2 == 0){
               System.out.println("Given Number is Even...");
            }else{
               System.out.println("Given Number is Odd...");
            }
	}
}

Output:

Enter a Number: 18
Given Number is Even...



Example 2: Java Program to Check whether a given number is even or odd without using If-else statement using ternary operator


In the below program, we are going to use the ternary operator to check whether the given number is even or odd. Since we are using the ternary operator, there is no need to use if-else statements. Here, we are just using the ternary operator to check whether the given number is even or odd. If the number is even, then "Even" will get stored in the result variable, and if the number is odd, then "Odd" will get stored in the result variable. Lastly, we are just printing the value of that result variable.

import java.util.Scanner;

public class EvenOddNumber
{
	public static void main(String[] args) {
	    
	    Scanner sc = new Scanner(System.in);
	    
            //Accept innput from user
	     System.out.println("Enter a Number: ");
             int num = sc.nextInt();
        
           //Checking even-odd using ternary operator
            String result = (num % 2 == 0) ? "Even" : "Odd";
        
            System.out.println("Given Number is "+result);
	}
}

Output:

Enter a Number: 9
Given Number is Odd

No comments:

Post a Comment

Share your thoughts or ask questions below!...👇

Featured Post

Java Interview Questions for 2 to 5 Years Experience

In this post, we are going to cover the most frequently asked Java interview questions for a 2 to 5 years experienced Java developer. It con...