Hi all, Why does s+=i; compile correctly but s = b*2; does not ? Given short s=1; byte b=1; int i=1; I think in both case right operands prometed to int. Isn't so ? Thanks Arun
Jim Hall
Ranch Hand
Joined: Nov 29, 2001
Posts: 162
posted
0
s += i; ---> s = (short) (s + i) Implicit cast.
Arun Mishra
Greenhorn
Joined: Jan 02, 2002
Posts: 16
posted
0
Why s=b*2 does not work like s=(short) b*2 ?
Regus Patoff
Greenhorn
Joined: Oct 30, 2001
Posts: 8
posted
0
It is the '*2' that is causing you to cast. 2 is an int to Java. So 'b*2' returns an int. You must cast the result of the calculation as a short. Check this out:
HTH, Regus
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
posted
0
Arun In the compound assignmnet operators there is an implicit cast to the type of the variable that the result is being assigned to. From the JLS Section 15.26.2
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. Note that the implied cast to type T may be either an identity conversion (�5.1.1) or a narrowing primitive conversion (�5.1.3).
Where as the normal 'extended' assignment operators do not have the implied cast. Hope that helps