Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Puzzler - casting a double to int

Tags:

java

int anInt = 1;
double aDouble = 2.5;

anInt = anInt + aDouble; // Error - need to cast double to int

anInt += aDouble; // This is ok. Why?

anInt = aDouble; // This is also an error.

anInt = 1 + aDouble; // This is also an error.

So my questions is: Why is it not a compile error to do anInt += aDouble?

like image 413
Tony Narvarte Avatar asked Mar 03 '15 13:03

Tony Narvarte


1 Answers

Three of the four cases properly report an error. Compound assignment is the only exception from the rule. Java Language Specification, part 15.26.2, explains why:

15.26.2 Compound Assignment Operators

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.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

As you can see, the error is avoided by implicit insertion of a cast.

like image 182
Sergey Kalinichenko Avatar answered Oct 21 '22 22:10

Sergey Kalinichenko