Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitives float and double: why does f+=d not result in Type Mismatch Error? [duplicate]

Tags:

java

primitive

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?

like image 203
sulai Avatar asked Dec 11 '12 14:12

sulai


People also ask

Which errors include type mismatch between operators and operands?

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.

What is a Mismatch error?

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.

What is type mismatch error in Java?

TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.


2 Answers

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

like image 120
kosa Avatar answered Nov 15 '22 08:11

kosa


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'
like image 44
Peter Lawrey Avatar answered Nov 15 '22 08:11

Peter Lawrey