Simple short addition yields warning

I found some questions concerning short arithmetic but none of them compared the following three cases. I wonder why these two pieces of code are ok

(a)

            short m = 1;
            m += m;

(b)

            short m = 1;
            m += m + m;

while this

(c)

            short m = 1;
            m = m + m;

leads to the error "Type mismatch: cannot convert from int to short" ?

Jon Skeet
people
quotationmark

It's not a warning - it's an error.

There are two facts at work here:

  • There's no short + short operator; the "smallest" addition is int + int, with a result type of int, and the operands are automatically promoted to int if necessary (see JLS 15.18.2)
  • Compound assignment operators always have an implicit cast (see JLS 15.26.2)

The second point is why the first two operations work. You've effectively got:

m = (short) (m + m);

And

m = (short) (m + m + m);

The first point is why the last operation doesn't work - the type of m + m is int, and you can't assign an int value to a short variable. (You need a cast...)

people

See more on this question at Stackoverflow