1
    byte b = 1;
    b = -b; //i get highlited in red in here
    
    int a = 1;
    a = -a; //it is ok for jvm

why if (b = -b), then I get a mistake, but if i do the same with int, it is OK? What is the reason?

Sorry for such a newbie question, but I can't understand reason myself, neither found answer in google of SO.

  • 2
    All Java integer operations are promoted to `int`, then assignments get made. So when you take `b` and multiply it by -1, it becomes an `int`. Then you have to tell the compiler it's ok to assign the `int` to a byte by casting it. – markspace Feb 04 '22 at 19:12
  • 1
    https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.15.3 – Sotirios Delimanolis Feb 04 '22 at 19:29

0 Answers0