2

I have a method that accept one parameter of type short.

public void doSomething(short value) {
   //DO STUFF
}

And I can call it this way:

short value = 3;
doSomething(value);

But not this another one:

doSomething(3);

Why? Is there a way to denote that this parameter is a short and not an int?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Héctor
  • 24,444
  • 35
  • 132
  • 243

3 Answers3

5

You can call it this way :

doSomething((short)3);

Without casting, 3 will always be an int literal.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

The reason

public void doSomething(short value) {
   //DO STUFF
}

can be called as

short value = 3;
doSomething(value);

cause value is already short

When you call it like doSomething(3); 3 is considered as integer and cannot be casted to short implicitly.

Basically doSomething(3); would require a

public void doSomething(int value) {
   //DO STUFF
}

method to go with.
However you can cast 3 to short and can call the method as: doSomething((short)3);

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
  • Thanks. Why there is not a way to denote a literal as `short` like `f` suffix in `float` types? – Héctor Apr 21 '15 at 08:58
  • @bigdestroyer The suffix does not have any special name in the Java Language Specification. Neither is there suffixes for any other integer types. So if you need short or byte literal, they must be casted – Darshan Lila Apr 21 '15 at 09:01
  • @DarshanLila _Neither is there suffixes for any other integer types_: what about `1L`? – Ben Win Apr 21 '15 at 09:08
  • @BenWin http://stackoverflow.com/questions/8860948/how-to-specify-a-constant-is-a-byte-or-short – Darshan Lila Apr 21 '15 at 09:10
  • @DarshanLila I know ;). I just said that there is a suffix for an "_integer type_" -> `L` – Ben Win Apr 21 '15 at 09:15
  • But, why? There is `f` for float, `d` for double, `L` for long, why there is nothing for short? Is there any reason? – Héctor Apr 21 '15 at 09:32
2

In Java, arithmetic expressions on the right hand side of the assignment evaluates to int by default. Look at this surprising example:

short a = 1;
short b = 2;

short c = a + b; // Error!

You need to explicitly cast to short as already mentioned in other answers, or change the method's signature to accept int instead.

It's worth mentioning that in terms of space short takes the same space as int if they are local variables, class variables or even instance variables since in most systems, variables addresses are aligned, I would simply change the signature of the method to accept an int instead and wouldn't complicate things.

Maroun
  • 94,125
  • 30
  • 188
  • 241