How are expressions evaluated in Java?

Asked

Viewed 329 times

6

Reading some references it was possible to understand the basic, 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;
    }
}

Translated explanation

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

  • Evaluation error may occur 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 the way the value is produced;

Doubts

  • What happens at each step of executing the expression?
  • Operands are considered individually or the increment is valid for the next operand, for example?
  • Very intriguing question! :)

1 answer

3

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

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

    int a = 1;
    a += 5; //a = 6
    
  • A prefix 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;, split:

s += - Compound allocation operator. The result of the sum of the value s with the result of the right expression is assigned to the variable s. Is equivalent to s = s + .....

s + mx(s) - At this time 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 To to that result(13).

+ ++s - s continues with the initial value. ++s, s is incremented in a unit and, as is a prefix operation, its output is used in the sum. The result is A + s+1(19), let’s call it B.

+ s - At this time s has the initial value incremented in one 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 attributed to him, 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.