Let’s learn even odd program in java using ternary operator.
Even odd program in java using ternary operator
Write a program to print even and odd numbers in java is one of the frequently asked interview question.
In the below java program to check whether the given number is even or odd first user enters a number using nextInt() method of Scanner class.
This number is stored in integer variable ‘number’.

Then if the given number is divisible by 2, then the number is even. Else the number is odd. Final result is stored in string variable “strOutput”.
Let’s write a program on even odd program using ternary operator.
import java.util.Scanner; public class EvenOddTernary { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a number : "); int number = sc.nextInt(); // java odd or even String strOutput = (number % 2 == 0) ? "even" : "odd"; System.out.println(number + " is " + strInput); sc.close(); } }
Output:
Please enter a number : 15
15 is odd
Also read – methods in java