Java后增量器的行为

Java后增量器的行为,java,post-increment,Java,Post Increment,为什么上面的代码打印1?我听说a++意味着你将得到a的值。然后增加它。但是上面的代码从未增加a,只是打印了1。有人能解释一下这里发生了什么吗?intb=a++相当于intb=a;a+=1。打印b时,a==2&&b==1intb=a++相当于intb=a;a+=1。当您打印b,a==2&&b==1时,它会按预期工作;下面是解释的代码: public static void main(String[] args) { int a = 1; int b = a++;

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

intb=a++
相当于
intb=a;a+=1
。打印
b
时,
a==2&&b==1
intb=a++
相当于
intb=a;a+=1
。当您打印
b
a==2&&b==1
时,它会按预期工作;下面是解释的代码:

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

    System.out.println(b);
}
这是相同的代码,但预增量为:

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
}

它按预期工作;下面是解释的代码:

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

    System.out.println(b);
}
这是相同的代码,但预增量为:

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++
就像说
a
——然后将
a
增加1。所以在你说
b=a++
之后,
b=1
a=2

如果要预增量
b=++a
,则在赋值之前会得到
b=2
预增量增量

结论

a++在递增之前赋值
++a递增,然后赋值


a++
就像说
a
——然后将
a
增加1。所以在你说
b=a++
之后,
b=1
a=2

如果要预增量
b=++a
,则在赋值之前会得到
b=2
预增量增量

结论

a++在递增之前赋值
++a递增,然后赋值


增量后含义=第一次完成分配,然后增量。 增量前含义=第一次增量,然后分配

例:

The reason is is as follow.

If it is i++, then equalent code is like this.

result = i;
i = i+1;
return result


If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i

So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)
如果


增量后含义=第一次完成分配,然后增量。 增量前含义=第一次增量,然后分配

例:

The reason is is as follow.

If it is i++, then equalent code is like this.

result = i;
i = i+1;
return result


If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i

So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)
如果


a
确实会递增。您正在打印
b
。您正在将a的值指定给b。递增的是,但b被指定为a++,那么递增的a会不会将该值指定给b?不,它将a的值指定给b,然后递增a。
a
会递增。您正在打印
b
。您正在将a的值指定给b。并且递增的是,但是b被指定为a++,那么增量a是否会将该值指定给b?不,它将a的值指定给b,然后递增a。感谢您提供了一个预递增的示例!也感谢您给出一个预增量示例!