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

673 views Asked by At

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.

3

There are 3 answers

3
Ted Hopp On BEST ANSWER

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

0
SASIKUMAR SENTHILNATHAN On

According to the Java Language the long value will only hold the suffix of L.

Refer

Java Primitive Data types

2
Arjit On

JAVA doesn't provide any suffix like S or s for short. You need to cast to shortusing (short)100.

Possible values are

int num = 20; //Decimal
int num = 020; //octal
int num = 0x20; //Hexadecimal
int num = 0b1010; //binary
long num = 563L; //long

In JDK 7, you can embed one or more underscores in an integer literal like

int num = 19_90;