0

I am using Java and new to it.

When I try

int integerValue = 100;
long longValue = 100;
integerValue = integerValue + longValue;

I get "Type mismatch: cannot convert from long to int".

But

integerValue+=longValue; 

works fine, which means it is doing the cast for me :)

Is it something that "+=" provides inherently? Any specific reason for that?

Edit: Oops!! Too common question! :) I should have thoroughly searched first, my bad!!

instanceOfObject
  • 2,936
  • 5
  • 49
  • 85
  • Duplicate of http://stackoverflow.com/questions/8272635/why-does-java-perform-implicit-type-conversion-from-double-to-integer-when-using – sw1nn Mar 13 '12 at 14:37
  • possible duplicate of [Varying behavior for possible loss of precision](http://stackoverflow.com/questions/2696812/varying-behavior-for-possible-loss-of-precision) – Louis Wasserman Mar 13 '12 at 14:50

5 Answers5

3

Yes, this is behaving exactly as section 15.26.2 of the JLS explains.

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You have uncovered the Tweedledum puzzle from the Java Puzzlers book. Basically the compound assignment performs type cast and regular one doesn't. See JLS for details.

MK.
  • 33,605
  • 18
  • 74
  • 111
1

Using the operation assignment operators, there is an implicit cast.

int i = 10;
i *= 5.5;
// same as
i *= (int) (i * 5.5);

or even

char ch = '5';
ch /= 1.1; // ch = '0'
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

That's correct. In your first example, you have to cast to int, because the result result of the left expression is a long value (only because longValue is long).

 integerValue = (long) (integerValue + longValue);  // this works

The += operator does the (same) casting implicity.

Both behaviours are specified in the Java Language Specification.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

Thanks everyone!

All answers were good enough!

Better explanations and examples available at stackoverflow.com/questions/8710619/java-operator :)

Community
  • 1
  • 1
instanceOfObject
  • 2,936
  • 5
  • 49
  • 85