variable-assignment =- meaning - Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j;
will not compile but i += j;
will compile fine.
Does it mean that in fact i += j;
is a shortcut for something like this
i = (type of i) (i + j)
?
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
The problem here involves type casting.
When you add int and long,
- The int object is casted to long & both are added and you get long object.
- but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But +=
is coded in such a way that it does type casting. i=(int)(i+m)
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception
.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
Subtle point here...
There is an implicit typecast for i+j
when j
is a double and i
is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j
where i
is an integer and j
is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j
to (int)
in this case for clarity.