Related Articles

Related Articles

Java Program To Find Largest Between Three Numbers Using Ternary Operator
  • Difficulty Level : Easy
  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output

Maximum number among 10, 25 and 15 is 25

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :