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));
}
}