java - Java 后递增器的行为

标签 java post-increment

    public static void main(String[] args) {
    int a = 1;
    int b = a++;

    System.out.println(b);
}

为什么上面的代码打印1?有人告诉我 a++ 意味着你会得到 a 的值。然后增加它。但上面的代码从未增加 a 并只是打印 1。有人可以解释一下这里发生了什么吗?

最佳答案

它按预期工作;代码解释如下:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // b is assigned the value of a (1) and THEN a is incremented.
    // b is now 1 and a is 2.
    int b = a++;

    System.out.println(b);
    // if you had printed a here it would have been 2
}

这是相同的代码,但预先递增了 a:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // a is incremented (now 2) and THEN b is assigned the value of a (2) 
    // b is now 2 and so is a.
    int b = ++a;

    System.out.println(b);
    // if you had printed a here it would have been 2 so is b.
}

关于java - Java 后递增器的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19970114/

相关文章:

java - 设置 GUI 元素大小的正确方法是什么?

java - 我无法理解 java.sql.date 的文档

java - 使用 CATALINA_OPTS 添加到 Tomcat 类路径

java - 是否有一个通用的 Java 实用程序可以将列表分成多个批处理?

java - x = x++ 不会递增,因为++ 是在赋值后应用的?

c - C 中的数组递增运算符

java - 如何a=3和b=4?

java - 跟踪鼠标光标android

c++ - 是返回 x++ 的行为;定义?

c - c 中增量运算的求值顺序