Even odd program in java using ternary operator

Let’s learn even odd program in java using ternary operator.

even odd program in java using ternary operator

Even odd program in java using ternary operator

In the below java program first user enters a number. This number is stored in variable number.

Also read – abstraction in java

Then if given number is divisible by 2, then even is returned. Else odd is returned. Final result is stored in string variable “strInput”.

Let’s see java program,

import java.util.Scanner;

public class EvenOddTernary
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a number : ");
      int number = sc.nextInt();
      // java odd or even
      String strInput = (number % 2 == 0) ? "even" : "odd";   
      System.out.println(number + " is " + strInput);
      sc.close();
   }
}



Output:

Please enter a number : 15
15 is odd

Using if else

Meanwhile we can check if an integer is odd or even using if else statement. Here in the below java program first user enters a number.

This number is stored in variable using sc.nextInt() method of Scanner class. To check whether number is even or odd, we divide the number by 2 and calculate its remainder using % operator.

To check the condition we use if else statement in java. If the given number is divisible by 2 then it is even number else odd number. Here’s the code,

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



Output:

Please enter a number : 66
66 is even