0

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" ?

Hartmut Pfitzinger
  • 2,304
  • 3
  • 28
  • 48
  • Related, http://stackoverflow.com/questions/8710619/java-operator – Masudul Apr 11 '15 at 14:07
  • Something fun (not really related to the question) that I once found: If we have `String s = null`, it will turn into `"null"` if you do `s += ""`. – Bubletan Apr 11 '15 at 14:07

1 Answers1

4

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...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194