Applying casting to primitive types

92 Views Asked by At
int a=128;
byte b;

b=(byte)a;

System.out.println(b);

This prints -128.

But in the Java book the same code outputs 0.

What's the difference between them?

4

There are 4 best solutions below

0
On

Right answer was posted already but id like to expand it a little.

To understand better how it works, try to read about it form other sources. @DanielGibbs provided few you could use

i suggest you also try to run code like:

    for (int a = -256; a < 256; a++) {
        byte b = (byte) a;
        System.out.println(a + " -> " + b);
    }

output of this code should let you see clearly meaning of less significant (and one most significant which determines sign) bites in int and how they are fit in byte type.

PS. -256 is not 10000000 00000000 00000001 00000000, but 11111111 11111111 11111111 00000000.

1
On

128 represented as a 32-bit integer (int) is 00000000 00000000 00000000 10000000 in binary.

As a byte is only 8 bits, when it is cast to a byte it becomes 10000000. Because all integers in Java are signed integers using two's complement, the first bit (1) is the sign bit, therefore the value becomes -128.

Not sure why the book said the output should be 0. Are you sure the example is exactly the same in the book?

More information on the Java primitives types here and Wikipedia has a fairly comprehensive article on two's complement.

0
On

Look, 128 = 0x80, so if you cut off all but less significant byte you will get 1000 0000 (binary). This is -128 for byte.
So there is an error in you java book:)

0
On

In Java this should really print -128. If a = 256 it should print 0. Byte is from -128 to 127, so if you cast 127 it is 127 and 128 is -128 because 127 + 1 = -128.