• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive casting

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I tried the following casting example :



I was expecting the compiler or runtime to throw some exception. But, lo behold, the output is -126. How ?
 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte range

-128 to 127= 256 unsigned

Hence casting will allow here to assign maximum 256 without any problem.

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meeta gaur wrote:byte range

-128 to 127= 256 unsigned

Hence casting will allow here to assign maximum 256 without any problem.



My question is not regarding the range of the byte primitive. How is 130L getting converted to -126 ? That is what I want to know.
 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SearchFirst

http://www.coderanch.com/t/544675/java-programmer-SCJP/certification/Primitive-Casting
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
 
Campbell Ritchie
Sheriff
Pie
Posts: 49813
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can’t assign 256 to a byte, signed or unsigned. That is outwith the range of bytes, signed or unsigned. The highest value of an unsigned byte (which you don’t get in Java) is 255.
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You can’t assign 256 to a byte, signed or unsigned. That is outwith the range of bytes, signed or unsigned. The highest value of an unsigned byte (which you don’t get in Java) is 255.


I believe what Meeta was trying to say was that we can store 256 different values (-127 through 0 to 128) and not value 256 itself.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49813
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that is correct. You get 2⁸ different values = 256.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic