Page 167 - Computer science 868 Class 12
P. 167

Let us see some more examples of increment/decrement operators.
                   1. If int a = 5, b = 6. Then find the value of
                     a = a++ + ++b + --a;
                 Ans. a = a++ + ++b + --a;
                       = 5 + 7 + 5
                       = 17

                   2. If int m = 10, n = 5; Then find the value of n += n++ * ++m / m;
                 Ans. n += n++ * ++m / m
                     n = n + (n++ * ++m / m)
                         = 5 + (5 * 11/11)
                       = 5 + (5*1)
                       = 10
                   3. int a = 11, b = 22, c;
                     c = a + b + a++ + b++ + ++a + ++b;

                     System.out.println("a = " +a);
                     System.out.println("b = " +b);
                     System.out.println("c = " +c);
                 Ans. a = 13
                     b = 24
                     c = 103
                   4. int a = 1, b = 2;
                     System.out.println(--b - ++a + ++b - --a);
                 Ans. 0
                   5. int m = 0, n = 0;
                     int p = --m * --n * n-- * m--;
                     System.out.println(p);

                   Ans. 1

                 Ternary Operator
                 The ternary operator works on three operands. It results in true or false according to the given expression.
                 Syntax:

                    variable = (logical expression)? true part:  false part;
                 Here, if the logical expression is true then the true part will be executed, else the false part will be executed.

                 Let us take a simple example to understand it better.

                    int m = 100, n = 10, k = 20, p;
                    p = (m>n && n>k) ? (m+k) : (m-n) ;
                 Explanation:  100>10 && 10>20 is false, so the false part (i.e., 100-10 = 90) will be executed. Hence, the output is 90.

                 6.5.8 Associativity and Precedence of Operators
                 Precedence and associativity are the features that deal with the operators used in Java. In an expression where there
                 is more than one operator, then it becomes necessary to know which operator to be executed first. This execution of
                 the operator according to the priority is done using the precedence and associativity of different operators.



                                                                                                                       165
                                                                                               Variables and Expressions   165
   162   163   164   165   166   167   168   169   170   171   172