3

Whenever I use byte or short data type as a method parameter, on method calls, I am required to explicitly cast the values I pass to those methods.

To better explain:

void foo(short x)
{}
void main() {foo((short)32);}

If I dont use short here then warning is generated.

method foo in class px cannot be applied to given types
required: byte
found: int

How can I get it better?

Gilberto
  • 893
  • 1
  • 13
  • 28
Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294

2 Answers2

4

No way out.

Java doesn't have a way to code byte or short literals. Any number literal is an int value and converting an int to a short without casting always creates a warning.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
3

Integer literals implicitly have the type int, and converting from an int to byte or short potentially loses information, so it requires explicit casting.

So don't use byte or short unless you really need to, which is very rarely the case.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • I was using short & byte so that I could efficiently manage the space... however I learnt somewhere that explicit casting has its own inefficiency problems.!? – Rajat Gupta Feb 24 '11 at 17:53
  • 1
    @Marcos: wrong on both accounts (and badly premature optimization even if it were correct). The CPU only works with int or long anyway, so using short or byte is actually potentially *less* efficient. Casting is not a problem at all. The *only* case where using byte or short can make sense is in large arrays. – Michael Borgwardt Feb 24 '11 at 21:00