Page 127 - CA_Blue( J )_Class10
P. 127

5          {
                   6              Scanner sc= new Scanner (System.in);

                   7              int n;
                   8              String r;

                   9              System.out.println("Enter a number:");
                  10              n=sc.nextInt();

                  11              r=(n>40)? "Greater than 40":"Not greater than 40";
                  12              System.out.println("Result is:"+r);

                  13          }
                  14      }

                 You will get the following output:
















                 7.3.1 Nested Ternary Operators
                 You can also nest ternary operators, which allows for evaluating multiple conditions in a single expression. However,
                 excessive nesting can reduce code readability, so it should  be used judiciously. The syntax of the nested ternary
                 operator is:
                 variable=(condition1)?valueIfTrue1:(condition2)?valueIfTrue2:valueIfFalse2;

                  Program 8    To input 3 numbers and print the greatest number.

                   1  import java.util.*;

                   2  class ternary_operator
                   3      {

                   4          public static void main()
                   5          {

                   6              Scanner sc= new Scanner(System.in);
                   7              int a,b,c,g;

                   8              System.out.print("Enter first number :");
                   9              a=sc.nextInt();

                  10              System.out.print("Enter second number :");
                  11              b=sc.nextInt();




                                                                                                                       125
                                                                                           Conditional Constructs in Java  125
   122   123   124   125   126   127   128   129   130   131   132