Thursday, September 4, 2025
HomeLanguagesJavaJava Program To Find Largest Between Three Numbers Using Ternary Operator

Java Program To Find Largest Between Three Numbers Using Ternary Operator

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

Time Complexity: O(1)
Auxiliary Space: O(1)

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS