Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:<
The problem here involves type casting.
When you add int and long,
But +=
is coded in such a way that it does type casting. i=(int)(i+m)
Very good question. The Java Language specification confirms your suggestion.
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);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class
file code.
Really a good thing to know
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
The main difference is that with a = a + b
, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b
, what it's really doing is typecasting b
to a type compatible with a
. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);