Java中x=x+y与x+=y的区别,体现强制类型转换

int x+=y其实是x=(int)(x+y)

直接见下面的代码示例:

public class testCasting { public static void main(String arg[]) { int a = 10; int b = 20; double d = 12.3; char c = 'c'; String s = "abc"; //下面输出:The result of a = a + b is:30 System.out.println("The result of a = a + b is:" + (a=a+b)); //下面输出:The result of a += b is:50 System.out.println("The result of a += b is:" + (a+=b)); //下面输出:The result of a += d is:62(这里体现了强制类型转换为int) System.out.println("The result of a += d is:" + (a+=d)); //下面输出:The result of a = a + d is:74(这里需要使用(int)d来进行强制转换,不然编译不过) System.out.println("The result of a = a + d is:"+ (a=a+(int)d)); //下面输出:The result of a = a + d is:86.3(这里体现表达式中最大的数据类型决定最终结果的数据类型) System.out.println("The result of a = a + d is:"+ (a+d)); //下面输出:The result of a = a + c is:173(这里体现了只要类型比int,那么在运算之前,这些值会自动转换为int) System.out.println("The result of a = a + c is:" + (a=a+c)); //下面输出:The result of a += c is:272 System.out.println("The result of a += c is:" + (a+=c)); //下面输出:The result of c += a is:ų(这里体现了c+=a其实是c=(char)(c+a)的实质,多了一层强制转换) System.out.println("The result of c += a is:" + (c+=a)); //下面输出:The result of s = s + a is:abc272(下面两个涉及String的操作,体现了String的特性,表达式中出现String开头的,之后的都会转换为String进行连接) System.out.println("The result of s = s + a is:" + (s=s+a)); //下面输出:The result of s += a is:abc272272 System.out.println("The result of s += a is:" + (s+=a)); //下面输出:The result of s = s + c is:abc272272ų System.out.println("The result of s = s + c is:" + (s=s+c)); } }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值