# the method "byteValue()" of Integer

weiliu lili
Ranch Hand
Posts: 46
What is the result of attempting to compile and run this ?
public class Test {

public static void main(String[] args){
Integer i = new Integer(256);
System.out.println(i.byteValue());
}
}
the result: Runs and prints "0"
why 0? I thought 256 is out of range of byte
thanks

Asif Mahmood
Greenhorn
Posts: 29
Yes, the output is correct. The maximum unsigned value that can be stored in byte is 255 (8 bits). If you see carefully, you'll observe that 9th bit will be 1 and all the low-order 8 bits will be 0, if the value is 256. byteValue() method returned the low-order 8 bits of 32-bit integer value. Since all the 8 bits are 0, the sum would also be 0.
Best regards,
-Asif

Jamal Hasanov
Ranch Hand
Posts: 411
Hi, Weiliu
I can suggest you to download Java API source (src.zip, maybe itr exists in your JDK\ directory ). Each time , when you meet such strange behaviour, open the .java file and analyse method code.
This method helps me much.
That's all.
Jamal Hasanov
www.j-think.com

weiliu lili
Ranch Hand
Posts: 46
I think the byte value should be -128 to 127,what does Mahamood mean by unsigned range 0 to 255

Corey McGlone
Ranch Hand
Posts: 3271
Originally posted by weiliu lili:
I think the byte value should be -128 to 127,what does Mahamood mean by unsigned range 0 to 255

I think Asif merely misspoke. A byte is a signed value and the greatest signed value that it can contain is 127. That would be 01111111. The most negative value that can be stored in a byte is -128, which is 10000000.
I hope that helps,
Corey

weiliu lili
Ranch Hand
Posts: 46

Jose Botella
Ranch Hand
Posts: 2120
This is the binary (int) for 256:
00000001 00000000
byteValue() acts as a conversion from int to byte resulting in:
00000000

Corey McGlone
Ranch Hand
Posts: 3271
Originally posted by Jose Botella:
This is the binary (int) for 256:
00000001 00000000
byteValue() acts as a conversion from int to byte resulting in:
00000000

To go along with what Jose is saying - the method byteValue() returns only the least significant byte from the Integer. As this byte contains nothing but 0's (see Jose's post), you get a result of 0.
Corey

Jose Botella
Ranch Hand
Posts: 2120
Well, obviously
00000001 00000000
is not an int
but a short.
But I think it conveys the idea

weiliu lili
Ranch Hand
Posts: 46
Originally posted by Jose Botella:
This is the binary (int) for 256:
00000001 00000000
byteValue() acts as a conversion from int to byte resulting in:
00000000

but if " Integer i = new Integer(129);" the result is -127.This is the binary(short)for 129
0000000 10000001 , how could this binary be converted to -127?
THANKS

Jose Botella
Ranch Hand
Posts: 2120
change 1 by 0 and viceversa:
1000 0001 -> 0111 1110
compute its value:
0111 1110 -> 126