How come the following work? byte a=2,b; b=a+1; // doesn't work - needs a cast b=a++; // it works, why? - shouldn't it need a cast? long L=1; int i=0; i=i+L; // not okay - needs a cast i+=L; // okay, why? - shouldn't it need a cast also?
The statement b = a++ works not because there is an automatic cast, but because a is incremented as a byte and assigned to b, which is also a byte. In the statement i = i + L the cast is automatic, and it is to a long type. A long won't fit into the int on the left side of the assignment operator, so you have to do an explicit cast to force the issue. The statement i += L works because of the compound operator; i becomes a long because the largest data type in the expression is a long. I hope this hslps. [This message has been edited by Barbara Dyer-Bennet (edited September 15, 2000).]
I tried the same with double i.e saying i+=d(where double d=1.0)and when i displayed it on console I'm getting int value and not as double as pointed out...(that the compound statement will be casted to largest data type in the expression) .
Joined: Nov 22, 2008
hi, i tried with bytes byte b1=1,int i=1;and when i perform b1+=1; it is giving explicit casting is required...i could not get to final conclusion on this..is there any version problem..