There is a number for example 115 , in the binary system this number is 01110011 , I need to declare this number as a literal so that it would be negative. I know how to do this with int , short , long , a problem in the type byte . Is it possible to initialize a variable of type byte with a literal with a negative value. What would be to see the number -115 when printing test1 ?

  byte test1 = 0B01110011; int test2 = 0B11111111_11111111_11111111_10001101; 

    1 answer 1

    This is because all integer literals in Java can be either int or long if the literal is terminated with an L or l ( JLS 3.10.1 ). Therefore, 0B10001101 perceived by the compiler as the number 141 . A variable of type byte can take values ​​in the range [-128..127], so the compiler does not allow to assign. Code

     byte c = 0B11111111_11111111_11111111_10001101; 

    at the same time it will not cause errors, since -115 is included in valid values ​​of type byte .

    Therefore it is necessary to force the type:

     byte b = (byte)0B10001101;