3

I encountered someting unexpected with the java += operator.

Apparently, this compiles:

int a = 0;
a += 3/2.0;
System.out.println(a);  // outputs "1"

While, this doesn't

int a = 0;
a = a + (3/2.0);   // eclipse compiler error "Type mismatch: cannot convert from double to int"
System.out.println(a);

Is this expected behaviour? I find it strange that the += operator does not report a "Type mismatch", because it is an 'add and assign' operator, where you add a double, which gives a double result, and is then assigned to an int variable. Instead it silently casts (and truncates) the result.

wvc
  • 91
  • 1
  • 3

3 Answers3

3

This is the way += has worked from C. It's "feature" not a bug

See Java's +=, -=, *=, /= compound assignment operators

BTW You can try this

char ch = '0';
ch *= 1.1; // ch = '4'

Also see a post of mine http://vanillajava.blogspot.com/2012/11/java-and-implicit-casting.html

Community
  • 1
  • 1
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    C does the narrowing conversion in the assignment without complaint, so that's not C legacy, that's a compromise made when making Java stricter than C and C++. – Sebastian Redl Jun 11 '13 at 09:48
  • 1
    The original [answer](http://stackoverflow.com/a/8710747/2024761)! – Rahul Jun 11 '13 at 09:50
  • @R.J Well spotted, but memory isn't so good some times ;) – Peter Lawrey Jun 11 '13 at 09:52
  • When java designers see simple `int d=1.3` as a compiler error instead of just a warning, how justified is it to make `int a+=3/2.0` compilable when it's equivalent sin? – pinkpanther Jun 11 '13 at 09:58
  • @pinkpanther I think it's an inconsistency which came about becuase they made assignment more strict but perhaps assumed that if you use an assignment operator you knew what you were doing. Given C allows implicit casts, they may not have thought it such a problem. – Peter Lawrey Jun 11 '13 at 10:01
2

int a = a + (3/2.0); doesn't compile since:

  • int + double leads to a double
  • a is referenced as an int
  • cast from double to int missing

int a += 3/2.0; compiles since:

  • int + double leads to a double
  • a is referenced as an int
  • double is castable to an int and luckily, compiler adds an implicit cast similar to:

    int a = (int)(a+ 3/2.0);. This is due to the special op= notation that is interpreted more cleverly from compiler than the basic assignment operator: =.

Mik378
  • 21,881
  • 15
  • 82
  • 180
0

This is not a bug , its a implicit conversion happened.

for eg.

Byte b=3;

b+=5;  //compiles

b=b+5; //doesnt compiles

Here what happens is

a=a+3/2.0;   // 3/2.0 produces double , it add int to double but cant convert it implicitly to int.

a += 3/2.0;  // here implicit conversion after addition of a to 3/2.0 happends from double to int
anshulkatta
  • 2,044
  • 22
  • 30