Tuesday 17 January 2012

Assignment vs compound assignment operator

Assignment operator ( = ) and compound assignment operators (like +=, -=, etc) do the same thing in the end, ie. assignment. But there is slight difference between assignment and compound operator.

Case 1 : Operands are primitive types
In this case that it silently casts the operand on the right side to the operand on the left side. So consider the following statement:
short x = 0;
int i = 123456;

So this expression will work:
x+=i //works

This will not:
x = x + i ; //compile time error -  "possible loss of precision"

To avoid unpleasant surprises, do not use compound assignment operators on variables of type byte, short, or char.

Case 2 : Case of objects
Consider following code:
Object x = "Raj ";
String i = "has taj";

Again here the case is opposite:
x = x + i ; //works

This will not work, because += will work for string, if rhs argument is string.

x+=i //error - incompatible types...


No comments:

Post a Comment