Java中的增量和减量运算符 [英] Increment and Decrement operators in java

查看:108
本文介绍了Java中的增量和减量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对增量和减量运算符有疑问.我不明白为什么Java会给出这些输出.

I had questions about incremental and decremental operators.I couldn't understand why java gave these outputs.

    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,而在第三个函数中,x函数与x + 1乘.据我所知,一元增量和一元减运算符的优先级高于算术运算符,那么为什么第二个运算符不增加1(y ++ * x = 3 * 2 = 6),为什么不(y + 1)* x = 8?

For example, in 2nd println function y is multiplicated without increasing 1 and in 3rd function x is multiplicated with x+1. As I know unary increment and unary decrement operators have higher precedence than arithmetic operators so why second one calculated without increasing 1( y++ * x = 3*2 = 6 there and why not (y+1) * x = 8 ?

推荐答案

 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)

这篇关于Java中的增量和减量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆