为什么在此忽略此Java运算符优先级? [英] Why is this Java operator precedence being ignored here?

查看:173
本文介绍了为什么在此忽略此Java运算符优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code prints out "3", not "4" as you might expect.

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

我理解如何。在加载a的值之后发生后缀增量。 (见下文)。

I understand how. The postfix increment happens after the value of "a" has been loaded. (See below).

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

What I don't quite understand is the why. The operator precedence of postfix ++ is higher than + so shouldn't it execute first?

% 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:  iload_1
   15:  invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   18:  return


推荐答案

Postfix ++ 增加变量的值,返回增量前的值 。因此,示例中 operator ++ 的返回值将是 1 ,当然还有 1 + 2 将提供 3 ,然后将其分配给 a 。到分配时, ++ 已经将 a 的值增加到 2 (因为优先级),所以 = 会覆盖递增的值。

Postfix ++ increments the value of variable, and returns the value that was there before the increment. Thus, the return value of operator++ in your example will be 1, and of course 1 + 2 will give 3, which is then assigned to a. By the time of assignment, ++ has already incremented the value of a to 2 (because of precedence), so = overwrites that incremented value.

这篇关于为什么在此忽略此Java运算符优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆