1

Integer Wrapper class

Integer obj = new Integer("1000");

System.out.println(obj.byteValue( )); //-24

I am not able to understand that how this output is formed. I want to understand how this "1000" in an integer is converted into "-24" in a byte. I want to know about the logic behind this.

Pshemo
  • 122,468
  • 25
  • 185
  • 269

2 Answers2

3

The docs say:

Returns the value of this Integer as a byte after a narrowing primitive conversion.

which isn't particularly helpful if you don't know what a "narrowing primitive conversion" is. Well, you can look into the Java Language Specification (section 5.1.3) for the definition of that:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

The Integer 1000 is represented by 32 bits:

00000000 00000000 00000011 11101000

byte is 8 bits, so we discard all but the 8 lowest order bits, we get:

11101000

which is -24 in 8-bit two's complement binary. -24 = -128 + 64 + 32 + 8

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

Casting an integer to a byte will give the last 8 bits of of the integer.

1000 in decimal -> 1111101000 in binary

Converting this to a byte value gives you 11101000 which is -24.

BayanR
  • 149
  • 9