Search code examples
javabytesignedprimitive-typestype-mismatch

Assigning a negative byte to itself


I'm facing this line of code.

byte b='b';
b=-b;

So b is now 98. But now the second line gives a type mismatch error(cannot convert from int to byte). Why is that? I read around, heard a lot of "all bytes are signed" but I still don't get it. A thorough answer would be greatly appreciated.


Solution

  • At first, it seems puzzling:

    b = 'b';
    

    Takes a wider type char which takes 2 bytes in memory, and puts it into a single byte. This shouldn't work. But it does.

    b = -b;
    

    Takes a negative byte and puts it in a byte. This should work, but it doesn't.

    The reason for the success of b = 'b' is actually the fact that 'b' is a constant expression. As such, the compiler identifies that it does not overflow a single byte, and therefore allows the assignment. If, instead of that, you had written:

    char c = 'b';
    byte b = c;
    

    this would have failed, because c is no longer a constant expression.

    The reason that the second assignment failed has already been explained to you in other answers. As soon as you apply the - operator to a byte, the result is an int. Once that happens, again, you can't put it in a byte because an int takes 4 bytes. But you can cast it.