Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

widening and narrowing ???

 
saiprasad raut
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic