Skip to content
Related Articles

Related Articles

Java Program To Find Largest Between Three Numbers Using Ternary Operator

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 02 Nov, 2020

Java offers a lot of Operators and one such operator is the Ternary Operator. It is a linear replacement for an if-else statement. Thus, it is a very useful operator and it uses less space in comparison to an if-else statement.

Ternary Operator Syntax :

variable = condition ? expression1 : expression2 ;

The same statement can be written in if-else statement as follows:

if(condition){
      variable = expression1 ;
}
else{
      variable = expression2 ;
}

Given three numbers we have to find the maximum among them by just using the ternary operator.

Example : 

Input  : a = 15 , b = 10 , c = 45
Output : 45

Input  : a = 31 , b = 67 , c = 23
Output : 67

Thus, we can make use of nested ternary operator to find the maximum of 3 number as shown below :

Java




// Java Program to Find Largest
// Between Three Numbers Using
// Ternary Operator
class MaximumNumber {
  
    // Main function
    public static void main(String args[])
    {
        // Variable Declaration
        int a = 10, b = 25, c = 15, max;
  
        // Maximum among a, b, c
        max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
  
        // Print the largest number
        System.out.println("Maximum number among " + a
                           + ", " + b + " and " + c + " is "
                           + max);
    }
}

Output

Maximum number among 10, 25 and 15 is 25

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!