File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes primitive casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "primitive casting" Watch "primitive casting" New topic
Author

primitive casting

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

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 ?


~ Mansukh
meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

byte range

-128 to 127= 256 unsigned

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


My one regret in life is that I am not someone else.
- Woody Allen
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

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

Joined: Dec 05, 2012
Posts: 305

SearchFirst

http://www.coderanch.com/t/544675/java-programmer-SCJP/certification/Primitive-Casting
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157



Thanks..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36520
    
  16
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

Joined: Jul 27, 2010
Posts: 1157

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

Joined: Oct 13, 2005
Posts: 36520
    
  16
Yes, that is correct. You get 2⁸ different values = 256.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: primitive casting
 
Similar Threads
casting
widening conversion
Assigning a byte to a long
Problem with casting
Explicit cast