相关疑难解决方法(0)

为什么在此忽略此Java运算符优先级?

以下代码打印出"3",而不是"4",如您所料.

public class Foo2 {
    public static void main(String[] args) {
        int a=1, b=2;             
        a = b + a++;
        System.out.println(a);
    } 
}
Run Code Online (Sandbox Code Playgroud)

我明白了.在加载"a"的值之后发生后缀增量.(见下文).

我不太明白的是为什么.postfix ++的运算符优先级高于+所以不应该先执行?

% javap -c Foo2

Compiled from "Foo2.java"
public class Foo2 extends java.lang.Object{
public Foo2();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_1
   1:   istore_1
   2:   iconst_2
   3:   istore_2
   4:   iload_2
   5:   iload_1
   6:   iinc    1, 1
   9:   iadd
   10:  istore_1
   11:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   14: …
Run Code Online (Sandbox Code Playgroud)

java post-increment

5
推荐指数
2
解决办法
2573
查看次数

Java算术表达式

以下表达式的计算结果为14。

    int a=4;
    int b=6;
    int c=1;
    int ans= ++c + b % a - (c - b * c);
    System.out.print(ans);
Run Code Online (Sandbox Code Playgroud)

这就是我的计算方式

    1. (c - b * c) // since bracket has highest preference
    ans : -5
    2. ++c //since unary operator has next highest preference
    ans : 2
    3. b%a // % has higher preference than + and -
    ans : 2
Run Code Online (Sandbox Code Playgroud)

因此,2 + 2-(-5)= 9

如您所见,我得到的值是9。不知道我的计算方式出了什么问题(很确定我最终会看起来很愚蠢)

编辑:我指的是以下链接的优先级和关联。 https://introcs.cs.princeton.edu/java/11precedence/

有人可以解释16级和13级括号之间的区别吗?我认为13级括号仅用于类型转换。这就是为什么我考虑使用16级括号来评估表达式。

java operators

3
推荐指数
1
解决办法
69
查看次数

标签 统计

java ×2

operators ×1

post-increment ×1