1

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.

augray
  • 3,043
  • 1
  • 17
  • 30
Code Cube
  • 51
  • 7
  • 2
    The fact that you are using Maven has no bearing on your question. Maven is not a compiler- it uses a compiler. Thus it doesn't really care about the syntax of your code. – augray Jun 11 '15 at 03:07
  • 2
    Just out of curiosity, what IDE is this that thinks Java allows an `S` suffix for integer literals? – Ted Hopp Jun 11 '15 at 03:31
  • @augray Ok, thank you for clearing that up. I didn't really know what part of the process maven did. – Code Cube Jun 12 '15 at 14:37
  • @Ted Hopp I am using Eclipse, and it accepted '10S' when I needed a short as a function argument. – Code Cube Jun 12 '15 at 14:37

3 Answers3

5

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

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • See also this [related question](http://stackoverflow.com/questions/2294934/setting-short-value-java). – augray Jun 11 '15 at 03:06
  • And this [oracle nutsandbolts](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) – blazetopher Jun 11 '15 at 03:07
  • Thank you, it makes sense now :) – Code Cube Jun 12 '15 at 14:37
  • [This thread](http://stackoverflow.com/questions/14297113/eclipse-bug-when-is-a-short-not-a-short) also has a bit of useful info about when you need to cast and when you can use an `int` literal without casting when you need a `short`. – Ted Hopp Jun 12 '15 at 14:46
0

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

Refer

Java Primitive Data types

0

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;
Arjit
  • 3,290
  • 1
  • 17
  • 18