0

I am seeing inconsistent behavior when using a simple assignment operation.

class TestInt {
    public static void main(String args[]) {
        byte a = 1, b = 1;
        b = b + a;
    }
}

causes TestInt.java:4: error: incompatible types: possible lossy conversion from int to byte b = b + a; ^ 1 error

whereas this compiles and works fine

class TestInt {
    public static void main(String args[]) {
        byte a = 1, b = 1;
        b += a;
    }
}

I do understand why the first piece of code may fail, I just cant figure out why there is a difference between the 2, coming from the C programming world.

  • Also here: http://stackoverflow.com/questions/21895078/why-is-the-sum-of-bytes-integer – Matthew Gunn Apr 23 '16 at 17:16
  • And here: http://stackoverflow.com/questions/8710619/javas-compound-assignment-operators – Alex Hall Apr 23 '16 at 17:17
  • Think of `=` and `+=` as two distinct assignment operators instead of mentally rewriting the second as the first. The `+` operator from variant 1 promotes the arguments to `int` producing an `int` which might cause the precision loss when converted back to `byte`. – collapsar Apr 23 '16 at 17:17
  • Thanks, the JLS explanation was exactly what I was looking for. – Rakesh Iyer Apr 24 '16 at 01:47

0 Answers0