Is the left-to-right order of operations guaranteed in Java?

后端 未结 10 1211
温柔的废话
温柔的废话 2021-01-04 10:16

Consider this function:

public static final int F(int a, int b) {
    a = a - 1 + b;
    // and some stuff
    return a;
}

Is it required

10条回答
  •  隐瞒了意图╮
    2021-01-04 10:53

    You can see here the operator precedence in Java: http://bmanolov.free.fr/javaoperators.php . Because + and - have the same precedence, they will be executed in the order in which they appear.

    If you want to be more clear about what which operation takes place first (or if you want to break the built-in precedence), you can (and should) use parantheses (( and )), like this:

    x = (a - b) + (c * (d - e))

提交回复
热议问题