Page 69 - CA_Blue( J )_Class10
P. 69

Let see some examples of assignment operators.
                 1.  If int a = 22, b = 2;
                   a += a + a--/--a + b                                                         [use of shorthand operator]
                   a   = a+ (a + a--/--a + b)
                        = 22 + (22+22/20 + 2)
                        = 22 + (22 + 1 + 2)
                        = 22 + 25
                        = 47
                 2.  if int a = 2, b = 3,c = 0;
                   c  -= ++a + (b++ % c)
                   c   = c - (++a + (b++ % c))
                        = 0 - (3 + (3 % 0))                                  [Error: java.lang.ArithmeticException: / by zero]
                 3.  if a = 20, b = 15;
                   b +=  a++ * 2 / a++ + b;
                   b   = b + (a++ * 2 / a++ + b)
                        = 15 + (20 * 2 / 21 + 15)
                        = 15 + (40 / 21 + 15)
                        = 15 + (1 + 15)
                        = 15 + 16
                        = 31

                 4.3.5 Ternary Operator
                 Ternary operator is also known as conditional operator. The result of the expression with ternary operator depends on
                 the logical expression. Syntax of ternary operator is:

                    Result = (Condition)? Statement1 : Statement 2;
                 If the conditional expression evaluates to true, then Statement1 will execute otherwise Statement 2 will execute. Let
                 us take some examples:

                    int a = 50, b= 40, result;
                    result = (a > b) ? (a + b) : (a - b) ;
                 The logical expression (a > b) will return true, so the output will be (a + b) = 90. Let us see some more examples of
                 ternary operators.
                 1.  int a=10,b=20,c;
                   c = (a > b) ? a : b;
                      = (10 > 20) ? 10 : 20;
                      = 20
                 2.  double sales = 2500, commission;
                   commission  = (sales >= 1000) ? 15.0/100.0 * sales: 10.0/100.0 * sales;
                               = (2500 >= 1000) ? 15.0/100.0 * sales: 10.0/100.0 * sales;
                               = 15.0/100.0*2500
                               = 375.0
                 3.  double sal = 20000, da = 0.0;
                   da = (sal <= 10000) ? 0.25 * sal : 0.3 * sal;
                     = (20000 <= 10000) ? 0.25 * 20000 : 0.3 * 20000;
                    = 6000.0

                 4.3.6 Some Special Operators in Java
                 Java provides two special operators which are dot(.) and new. Let us learn about these in detail.



                                                                                                                       67
                                                                                                      Operators in Java   67
   64   65   66   67   68   69   70   71   72   73   74