java程序设计及应用 增量式,Java中的增量和减量运算符

这篇博客探讨了Java中增量和减量运算符的使用,特别是在表达式求值顺序中的行为。例如,`y++*x` 和 `x*x++` 的结果可能与预期不同,因为运算符的优先级和结合性导致了计算的复杂性。解释了为何在某些情况下,如`y++*x` 不会立即增加y的值,而在`x*x++` 中x的增值发生在乘法之后。
摘要由CSDN通过智能技术生成

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

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值