简体   繁体   English

增量运算符如何在Java中运行?

[英]How does the increment operator behave in Java?

Why is the result 8 and not 9? 为什么结果是8而不是9?

By my logic: 按我的逻辑:

  1. ++x gives 4 ++x给出4
  2. 4 + 4 gives 8, so x = 8 4 + 4给出8,所以x = 8
  3. But after that statement x should be increased due to x++ , so it should be 9. 但是在那个语句之后x应该由于x++而增加,所以它应该是9。

What's wrong with my logic?: 我的逻辑出了什么问题?:

int x = 3;
x = x++ + ++x;
System.out.println(x); // Result: 8 

You should note that the expression is evaluated from the left to the right : 您应该注意,表达式从左到右进行评估:

First x++ increments x but returns the previous value of 3. 第一个x++递增x但返回前一个值3。

Then ++x increments x and returns the new value of 5 (after two increments). 然后++x递增x并返回新值5(在两个增量之后)。

x = x++ + ++x;
    3   +  5     = 8

However, even if you changed the expression to 但是,即使您将表达式更改为

x = ++x + x++;

you would still get 8 你仍然会得到8

x = ++x + x++
     4  +  4   = 8

This time, the second increment of x ( x++ ) is overwritten once the result of the addition is assigned to x. 这次,一旦将加法结果赋给x,就会覆盖x( x++ )的第二个增量。

++x is called preincrement and x++ is called postincrement. ++ x称为preincrement,x ++称为postincrement。 x++ gives the previous value and ++x gives the new value. x ++给出前一个值,++ x给出新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM