Page 184 - Computer science 868 Class 12
P. 184

Output:
              Input the 1st number: 67

              Input the 2nd number: 58
              Input the 3rd number: 98
              The greatest number is : 98

              7.2.2 Ternary Operator
              It is a one-line expression of the if else statement in Java. Like if-else, it evaluates the condition to be tested and
              depending on the result of the condition executes a block of code.

              Syntax:
                  result = (test condition)? Expression executed if condition satisfied: expression
                  executed if condition not satisfied;
              Converting if-else to the ternary operator and vice-versa

              Let us take some examples for better understanding.

              Example 1: // Using if-else
                  int a = 6, b = 7;
                  if(a==b)
                      System.out.println("Numbers are equal");
                  else
                      System.out.println("Numbers are not equal");
                  // Using Ternary Operator
                  int a = 6, b = 7;
                  System.out.println((a==b)? "Numbers are equal" : "Numbers are not equal");
              Example 2: // Using if-else

                  String result;
                  if(marks>40)
                  result = "pass";
                  else
                  result = "fail";

                  // Using Ternary Operator

                  String result = (marks > 40) ? "pass" : "fail";

              Nested ternary operator
              Similarly, a nested if else can be explained using a nested ternary operator.

              Example 3: // Using if-else


                  int least_number;
                  if(var1 <= var2)
                  {
                      if(var1 <= var3)
                      least_number = var1;
                      else
                      least_number = var2;
                  }
                  else
                  {


                182182  Touchpad Computer Science-XII
   179   180   181   182   183   184   185   186   187   188   189