jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes Casting int value to Byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting int value to Byte" Watch "Casting int value to Byte" New topic
Author

Casting int value to Byte

Mohamed Alla Pitchai
Greenhorn

Joined: Oct 18, 2007
Posts: 12
Hello guys,
Consider the following code snippet.

int x = 241;
byte y = (byte) x;

System.out.println("y is " + y);

I am getting the output as -15. How did the result come as -15.
Please explain.

Thanks,
Mohamed
praveen Shangunathan
Ranch Hand

Joined: Sep 06, 2005
Posts: 65
byte can take only 8 bits with the 8th bit for sign(+ or -)
241 = 11110001
2's complement of 1110001 is 1111 which is 15.
Mohamed Alla Pitchai
Greenhorn

Joined: Oct 18, 2007
Posts: 12
Why do we want to do the 2's complement ?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

You don't, it's just easy to determine the value of a negative binary number. If the two's complement is 15, the value is -15.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
praveen Shangunathan
Ranch Hand

Joined: Sep 06, 2005
Posts: 65
thats the way -ve numbers are represented.
if the 8th bit is 0 then its a +ve number and you "convert" the remaining 7 bits to find the integer value.
if the 8th bit is 1 then we are looking at a -ve number. so you 2's complement the remaining 7 bits, get
integer value and put a - in front.
Manish Khurana
Greenhorn

Joined: Jan 26, 2008
Posts: 23
you do not actually need to cast to byte in your assignment. Let Mr compiler sweat it out and do some thing worthwhile for qa change except for pointing your errors. it does same for char and short (downcasts).
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

Originally posted by Manish Khurana:
you do not actually need to cast to byte in your assignment.

Yes you do.

For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast.
Doug Slattery
Ranch Hand

Joined: Sep 15, 2007
Posts: 294
you do not actually need to cast to byte in your assignment.

You also need the cast because you are downcasting from an int to a byte (a bigger bucket to a smaller). You don't need the cast going the other way (byte to int).

Aloha,
Doug

-- Nothing is impossible if I'mPossible
Manish Khurana
Greenhorn

Joined: Jan 26, 2008
Posts: 23
Sorry my mistake i think i was wrong . Thanks for correcting me
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting int value to Byte