Search code examples
javacastingjava-7short

Java: must cast to short, cannot use shorthand 'S'


I am trying to call a function that requires a short value. The following works:

i.setDamage((short) 10);

However, this does not:

i.setDamage(10S);

According to the IDE I am using, this should work. Why does it not? I am using Maven and Java 7.


Solution

  • According to the Java Language Specification, Section 3.10.1, the only integer type suffix for integer literals is L (or lower case l).

    An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

    The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

    You'll just have to stick with a cast. (Although you may be able to just use the integer literal without a cast if the value is in range.)