tags:

views:

239

answers:

3
+6  Q: 

java += question

Why does:

public class Addition { 
public static void main() { 
int a = 0; 
double b = 1.0; 
a = a + b;
System.out.println(a); 
} }

not compile but:

public class Addition { 
public static void main() { 
int a = 0; 
double b = 1.0; 
a  += b; 
System.out.println(a); 
} }

compiles.

+15  A: 

int = int + double is essentially

int = double + double

and you cannot do that without casting...

The int += double forces the result to an int while the other one requires casting.

So a = (int)(a + b);

should compile.

Edit: as requested in the comments... here is a link to more reading (not the easiest read, but the most correct info): http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2

TofuBeer
could you provide some link on that for further reading? Thanks
hhafez
i think the "deep" reason is because it's disallowed to assign while narrowing: byte = int is disallowed and int = double too. would one do a simple byte a; a += 2; and fail to compile, people would throw shoes at java. but i would still have liked extra rules that make it work without that cast :(
Johannes Schaub - litb
I'm not certain there is a deep reason, but the Java language specification explicitly defines the implicit cast: http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304
DefLog
+10  A: 

In Java += operator has an implicit cast to the left hand type. This goes for all composed operators.

DefLog
I think this is a more concise answer
matt b
+1  A: 

double + int returns double, so double = double + int is legitimate, see JLS 5.1.2 Widening Primitive Conversion on the other hand int = double + int is "Narrowing Primitive Conversion" and requires explicit cast

devdimi