aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please explain....!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Please explain....!!!!" Watch "Please explain....!!!!" New topic
Author

Please explain....!!!!

Arun Mishra
Greenhorn

Joined: Jan 02, 2002
Posts: 16
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
s += i; ---> s = (short) (s + i) Implicit cast.
Arun Mishra
Greenhorn

Joined: Jan 02, 2002
Posts: 16
Why s=b*2 does not work like s=(short) b*2 ?
Regus Patoff
Greenhorn

Joined: Oct 30, 2001
Posts: 8
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
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


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain....!!!!
 
Similar Threads
conversion prb
Shift operators
Unsigned bit shift
Q how does the above code give error and the code below doesn't???
Casting question