aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes widening and narrowing ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "widening and narrowing ???" Watch "widening and narrowing ???" New topic
Author

widening and narrowing ???

saiprasad raut
Ranch Hand

Joined: Aug 29, 2003
Posts: 40
when i compile and run the following code it goes well.



but if i compile the following i get loss od precision. i know if you directly say byte x = y + 1; it converts to int.but why not in the following code

Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The compound assignment operators include an implicit cast. Therefore, this code:



Is really equivalent to:



The Bitwise Complement Operator (~), however, includes no such cast. Instead, it promotes the operand to an int and returns it. As you can't assign an int to a byte, you get an error. If you want to assign that value to your byte variable, you'll have to include your own cast.

You can read more about that operator in the JLS, §15.15.5 Bitwise Complement Operator ~.

Corey


SCJP Tipline, etc.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The bitwise inversion operator ~ is applied to the value of x. The byte in x is widened to an int before being inverted. It's still an int after being inverted. To assign it to a byte you must use a cast to let the compiler know that you are aware of the possibility of loss of precision.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
 
subject: widening and narrowing ???