我遇到了一些意外的java + =运算符。
显然,这会编译:
int a = 0;
a += 3/2.0;
System.out.println(a); // outputs "1"
虽然,这不是
int a = 0;
a = a + (3/2.0); // eclipse compiler error "Type mismatch: cannot convert from double to int"
System.out.println(a);
这是预期的行为吗?我发现奇怪的是+ =运算符没有报告“类型不匹配”,因为它是一个'add and assign'运算符,你在其中添加一个double,它给出一个double结果,然后分配给一个int变量。相反,它会静默地转换(并截断)结果。
答案 0 :(得分:3)
这是+ {从C
起作用的方式。它的“功能”不是错误
请参阅Java's +=, -=, *=, /= compound assignment operators
BTW你可以试试这个
char ch = '0';
ch *= 1.1; // ch = '4'
另见我的帖子http://vanillajava.blogspot.com/2012/11/java-and-implicit-casting.html
答案 1 :(得分:2)
int a = a + (3/2.0);
自编译后无法编译:
int
+ double
会导致double
a
被引用为int
double
投射到int missing int a += 3/2.0;
编译自:
int
+ double
会导致双重a
被引用为int
double
可以转换为int
,幸运的是,编译器添加了类似于的隐式转换:
int a = (int)(a+ 3/2.0);
。这是因为编译器比基本赋值运算符更加巧妙地解释了特殊的op=
表示法:=
。
答案 2 :(得分:0)
这不是一个错误,它发生了隐式转换。
例如。
Byte b=3;
b+=5; //compiles
b=b+5; //doesnt compiles
这里发生的事情是
a=a+3/2.0; // 3/2.0 produces double , it add int to double but cant convert it implicitly to int.
a += 3/2.0; // here implicit conversion after addition of a to 3/2.0 happends from double to int