java中的增量和减量运算符

java中的增量和减量运算符,java,increment,operator-keyword,decrement,Java,Increment,Operator Keyword,Decrement,我对递增运算符和递减运算符有疑问,我不明白为什么java会给出这些输出 x = 5; y = 10; System.out.println(z = y *= x++); // output is 50 x = 2; y = 3; z = 4; System.out.println("Result = "+ z + y++ * x); // output is Result = 46 x = 5; System.out.println( x++*x

我对递增运算符和递减运算符有疑问,我不明白为什么java会给出这些输出

    x = 5;  y = 10;
    System.out.println(z = y *= x++); // output is 50
    x = 2; y = 3; z = 4;
    System.out.println("Result = "+ z + y++ * x); // output is Result = 46
    x = 5;
    System.out.println( x++*x); // output is 30
    x = 5;
    System.out.println( x*x++); // output is 25

例如,在第二个println中,函数y被乘法而不增加1,在第三个println中,函数x被乘法为x+1。正如我所知,一元增量和一元减量运算符的优先级高于算术运算符,所以为什么第二个运算符的计算不增加1(y++*x=3*2=6,为什么不增加(y+1)*x=8?

后缀-
++
表示以当前值计算变量,在计算周围表达式后,变量递增。

y++将在代码后向y添加1。
++y将在代码前向y添加1。

需要了解的内容:

增量后运算符(
++
在变量名之后)返回变量的旧值,然后对变量进行增量。因此,如果
x
5
,则表达式
x++
的计算结果为
5
,并且具有将
x
设置为
6
的副作用

这个有点特别:

x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46

请注意,这里使用的是字符串连接。它先打印
结果=
,然后打印
4
,这是
z
的值,然后是
y++*x
的值,这是
6
46
不是一个数字,它是一个
4
和一个
6
从两个表达式中放在后面。

T它们的优先级高于二进制运算符,但它们的计算结果为“x”。后递增的副作用不属于优先级的一部分。

因为使用
y++
y
将首先计算,然后递增

 x = 5;  y = 10;
    System.out.println(z = y *= x++); // output is 50 -->z=y=y*x i.e, z=y=10*5 (now, after evaluation of the expression, x is incremented to 6)
    x = 2; y = 3; z = 4;
    System.out.println("Result = "+ z + y++ * x); // output is Result = 46 --> from Right to left . y++ * x happens first..So, 3 * 2 = 6 (now, y will be incremented to 4) then "Result = " +z (String) + number (y++ * z) will be concatenated as Strings.
    x = 5;
    System.out.println( x++*x); // output is 30 --> 5 * (5+1 i.e, x is already incremented to 6 when you do x++ so its like 5 *6 )
    x = 5;
    System.out.println( x*x++); // output is 25 -- > 5 * 5 (x will be incremented now)

相反,使用
++y
时,增量发生在求值之前。

您的第一个表达式
z=y*=x++
等于:

z=y=y*x;
x++;
z + ""+ (y*x) // here z = 4 and y*x is 6 which gives us 46.
您的第二个表达式
+z+y++*x
相当于:

z=y=y*x;
x++;
z + ""+ (y*x) // here z = 4 and y*x is 6 which gives us 46.

同样地,你也可以找到第三和第四个表达式。

我建议阅读本教程,我认为这将有助于了解其用法->

让我们把它分成几部分:

x = 5;  y = 10;
System.out.println(z = y *= x++);
在上面的代码中,对于y*=x++的结果,有一个赋值给z;这意味着y=y*x++。现在,x++将在乘法完成后进行求值。如果您想在乘法之前进行求值,应该使用++x

x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46
在本例中,您将一个字符串与上面的值连接起来;乘法将是第一个,然后是加法,最后只计算后增量


其余的示例与上面的示例类似。运算符优先级是上面应用的规则,您可以使用此表查看它们的求值顺序:

您将运算符优先级与求值顺序混淆了。如果只计算优先级,那么为什么还要麻烦使用
y++
++y
?:)对于第二行,如果在后面的行中使用变量y,y将得到值“4”。这与运算符的算术排序无关,其中*优先于+。preincrement运算符立即使用递增的值,而postincrement运算符在执行操作后立即递增该值。感谢您的评论。我基本上明白了。