How do you evaluate expressions in Java?

6

Reading some references was possible understand the basics, but not enough to decipher the following code:

public class Expression {

    public static void main(String[] args) {
        int s = 5;
        s += s + mx(s) + ++s + s;
    }

    static int mx(int s) {
        for (int i = 0; i < 3; i++) {
            s = s + i;
        }
        return s;
    }
}

Explanation translated

  • First, the left operand (of the assignment) is evaluated to produce a variable: In this case without mystery, because it is s ;

  • There may be an evaluation error on both sides, which interrupts the evaluation: But this is not the case;

  • Then the right operand is evaluated and produces a value: here the explanation is very summarized, not making clear how the value is produced;

    >

Questions

  • What happens at each expression execution step?
  • Are the operands considered individually or is the incremental value for the next operand, for example?
asked by anonymous 29.03.2017 / 02:51

1 answer

3

The interpretation is simple if you understand what are compound assignment operators and suffix / prefix operators.

  • The compound assignment operator performs the operation between the two operands and assigns the result to the first operator.

    int a = 1;
    a += 5; //a = 6
    
  • A prefixal operator first applies the operation and then returns the result.

    int a = 1, b;
    b = ++a; //b = 2, a = 2
    
  • A suffix operator, first returns the value of the operand and then applies the operation.

    int a = 1, b;
    b = a++; //b = 1, a = 2
    

Let's look at the expression s += s + mx(s) + ++s + s; , in parts:

s += - Compound assignment operator. The result of adding the value s to the result of the expression on the right is assigned to the variable s . It is equivalent to s = s + .... .

s + mx(s) - At this point s has the initial value (5). This value is passed to the function mx() and the value returned (8) is added to s , let's call A to that result (13).

+ ++s - s continues with the initial value. ++s , s is incremented by one unit, and since it is a prefixal operation, its result is used in the sum. The result is A + s+1 (19), let's call it B .

+ s - At this point s has the initial value incremented by a unit (6), it is added to B , the result of B + 6 is 25 ( C ).

The right part ( C ) is calculated, it is now added to the initial value of s and the result assigned to it, remember that s += is equivalent to s = s + .... .

Thus, the final value of the expression is 30 ( 5 + C ) and is assigned to the variable s .

    
29.03.2017 / 13:37