3
class Tester {
    public static void main(String[] arg) {
        byte b=10;
        b +=(b<127)?b>-128? b+=10 :0 :5;
        System.out.println(b);
    }
}

i know that the conditions are evaluated true and took the control to b+=10 so now logically b+=b+=10; is adding the value of b and 10 which evaluates 20, assigning to b. Now i'm unable to evaluate it further.

2 Answers2

2

JLS 15.7.1. Evaluate Left-Hand Operand First has a similar example :

If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.

Example 15.7.1-2. Implicit Left-Hand Operand In Operator Of Compound Assigment

In the following program, the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition operator is evaluated, at which point the variable is set to 3.

class Test2 {
    public static void main(String[] args) {
        int a = 9;
        a += (a = 3);  // first example
        System.out.println(a);
        int b = 9;
        b = b + (b = 3);  // second example
        System.out.println(b);
    }
}

This program produces the output:

12
12

Therefore, in your case, the original value of b (10) is remembered and added to the result of the ternary conditional operator (which is 20, since the value of b+=10 is the result of that expression), giving you 30.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

First (b<127) is evaluated which is true so it moves to part b>-128? b+=10 In this b>-128 is evaluated which is also true so it moves to b+=10 which makes b=20 and adds to the left side of expression in which value of 10 is stored in b.So b+=(b=20) makes b=30

Loki
  • 801
  • 5
  • 13
  • If this were the case, then b=20 makes b equal to twenty, and then `b += (b=20)` would make it 40. The crucial step is that the very first thing that is done is that the original value of b is saved (10), and that the compound assignment operator adds the value of the right side of the expression to the original saved value of the left side. – Erwin Bolwidt Jul 28 '16 at 07:15