Monday, April 25, 2011

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.

From stackoverflow
  • 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

    hhafez : could you provide some link on that for further reading? Thanks
    Johannes Schaub - litb : 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 :(
    DefLog : 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
  • In Java += operator has an implicit cast to the left hand type. This goes for all composed operators.

    matt b : I think this is a more concise answer
  • 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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.