Possible Duplicate:
Java += operator
Code example:
double d = 1;
float f = 2;
f += d; // no error?
f = f+d; // type mismatch error, should be f = (float) (f+d);
So why does f+=d
not produce an error (not even at runtime), although this would decrease the accuracy of d
?
Type mismatched is another compile time error. The semantic error can arises using the wrong variable or using wrong operator or doing operation in wrong order.
Sometimes, while writing code, programmers may ask that a value be stored in a variable that is not typed correctly, such as putting a number with fractions into a variable that is expecting only an integer. In such circumstances, the result is a type-mismatch error.
TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.
As per JLS 15.26.2
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
That means:
f += d;
would become as
f = (float) (f+d);
The compount assignment does an implicit cast.
a #= b;
is equivalent to
a = (cast to type of a) (a # b);
Another example
char ch = '0';
ch *= 1.1; // same as ch = (char)(ch * 1.1);
// ch is now '4'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With