更新时间:2022-05-16 01:43:58
到目前为止,几乎所有人都对运算符优先级的求值顺序感到困惑.在Java中,优先级规则使表达式等同于以下内容:
Almost everybody so far has confused order of evaluation with operator precedence. In Java the precedence rules make the expression equivalent to the following:
a + (b * c) / ( d - e )
因为*
和/
具有相同的优先级,并且保持关联性.
because *
and /
have equal precedence and are left associative.
评估顺序严格定义为首先是左操作数,然后是右操作数,然后是(||和&&除外).因此,评估顺序为:
The order of evaluation is strictly defined as left hand operand first, then right, then operation (except for || and &&). So the order of evaluation is:
a
b
c
*
d
e
-
/
+
评估顺序在页面上.缩进反映了语法树的结构
order of evaluation goes down the page. Indentation reflects the structure of the syntax tree
修改
回应Grodriguez的评论.以下程序:
In response to Grodriguez's comments. The following program:
public class Precedence
{
private static int a()
{
System.out.println("a");
return 1;
}
private static int b()
{
System.out.println("b");
return 2;
}
private static int c()
{
System.out.println("c");
return 3;
}
private static int d()
{
System.out.println("d");
return 4;
}
private static int e()
{
System.out.println("e");
return 5;
}
public static void main(String[] args)
{
int x = a() + b() * c() / (d() - e());
System.out.println(x);
}
}
产生输出
a
b
c
d
e
-5
清楚地表明乘法是在减法之前 执行的.
which clearly shows the multiplication is performed before the subtraction.