简体   繁体   English

java代码输出背后的原因是什么?

[英]what will be the reason behind the output of java code?

Consider the following simple java code 考虑以下简单的Java代码

public static void main(string args[])
{
  int x=10;
  int y;

  y=x++;
  y=y--;

  System.out.println(y);
}

here output is 10. but actually y variable decrements. 这里的输出是10,但实际上y变量递减。 but according to me output should be 9. what is the reason? 但是根据我的输出应该是9.是什么原因?

The postfix-increment operator works as follows: 后缀递增运算符的工作方式如下:

  • Increment the operand 递增操作数
  • Return the previous value of the operand 返回操作数的前一个值

The postfix-decrement operator works as follows: 后缀减量运算符的工作方式如下:

  • Decrement the operand 减少操作数
  • Return the previous value of the operand 返回操作数的前一个值

Therefore, the following piece of code works as follows: 因此,以下代码段的工作方式如下:

x = 10;  // x == 10
y = x++; // x == 11, y == 10
y = y--; // y ==  9, y == 10

As you can see, y = y-- is equivalent to y = y . 如您所见, y = y--等效于y = y

It has no effect on the value of y at the end of the operation. 在操作结束时,它对y的值没有影响。

You need to understand about prefix and postfix operators. 您需要了解前缀和后缀运算符。

y=x++ means assign x to y and then increment x by 1; y=x++表示将x分配给y,然后将x递增1;

y=++x means increment x and then assign the incremented value to y. y=++x表示递增x,然后将递增的值分配给y。

If you understand this difference then its obvious what the code does. 如果您了解这种差异,那么代码的作用就显而易见了。

The post-decrement operator returns the old value of the variable. 后减运算符返回变量的旧值。 So when you write 所以当你写

y = y--;

it decrements y , then assigns the old value back to y . 递减y ,然后将旧值分配回y It's as if you wrote: 就像您写了一样:

old_y = y; // Save old value
y = y - 1; // perform y-- decrement
y = old_y; // Assign the saved value

Here's whats happening 这是怎么回事

int x=10; 

declare a vaiable x and assign 10 to it. 声明一个可变x并为其分配10。

int y;

declare a variable y 声明变量y

y=x++;

increment x therefore x=11 and return its old value therefore y=10

y=y--;

decrement y therefore y=9 at current point, and return its old value which is 10 and is caught by y therefore y=10 now. 因此,在当前点将y递减y = 9,然后返回其旧值10,并被y捕获,因此现在y = 10。

System.out.println(y);

Output 输出量

10

x = 10; x = 10; // x == 10 // x == 10

y = x++; y = x ++; //Here First Y is asigned with value 10 and increments x by 1 //这里,第一个Y赋值为10,x递增1

y = y--;//Here First Y is asigned with value 10 and decrements y by 1 y = y-; //在此,第一个Y赋值为10,y减1

Because If we use Postincrement or postdecrement First it asigns value to Variable then it performs increment or decrement . 因为如果我们先使用Postincrement或postdecrecrement,则将值赋给Variable,然后执行递增或递减操作。

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

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