Write A Program In Java To Find Maximum Of Three Numbers Using Conditional Operator

0

Write A Program In Java To Find Maximum Of Three Numbers Using Conditional Operator.

Write A Program In Java To Find Maximum Of Three Numbers Using Conditional Operator

In this program, we will create a java program to find the maximum of three numbers with the use of java conditional operator also known as ternary operator.

 

In java, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. It has the following syntax:


Syntax
Condition ? Value1 : Value2


Here, condition is a boolean expression that is evaluated first. If it is true, then the value of the expression is value1. If it is false, then the value of the expression is value2.


Let's use the conditional operator in a java program to find the maximum of three numbers.


Program

public class FindMaxOfThreeNumbers
{
     public static void main(String[] args)
     {
         int num1 = 10;
         int num2 = 20;
         int num3 = 15;
   
        int max = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
   
        System.out.println("The maximum of the three numbers is: " + max);
     }
}

Output
The maximum of the three numbers is: 20

Explanation
In the program first initializes three variables num1, num2, and num3 to the values 10, 20, and 15, respectively.

Then, using the conditional operator (?:), the program finds the maximum of the three numbers by checking if num1 is greater than num2. If it is, then it checks if num1 is also greater than num3. If it is, then num1 is the maximum. Otherwise, num3 is the maximum. If num1 is not greater than num2, then it checks if num2 is greater than num3. If it is, then num2 is the maximum. Otherwise, num3 is the maximum.

Finally, the program prints the maximum of the three numbers. In this case, the output will be The maximum of the three numbers is: 20.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)