Search code examples
javacompiler-optimizationshort

What is the difference between short/byte inside a parameter and inside a block


Possible Duplicate:
Eclipse bug? When is a short not a short?

In Java I can assign a short or a byte inside blocks like this:

short s = 20000;
byte  b = 120;

Because 20000 is a short value and 120 is a byte value, if I attempt to try:

short s = 67000;
byte  b = 128;

I will get an error that states it cannot compile from int to byte where

byte b = (byte)12232;

will not even trigger a warning that value may get lost. In a function call I'm forced to cast it anyways:

void test(short s){}
test(1) //invalid
test((short)1) //valid

While on return types it is okay again.

short test(){
    return 1; //valid
}

Why does the compiler sometimes deside to know the bounds of numbers (at least from constants), while it seem that it forgets it elsewhere?


Solution

  • Integral numeric literals in Java are of just two kinds: int (which are declared as 123), and long (which are declared as 123L).

    • short s = 1 is allowed because it is an assignment and a narrow conversion is allowed there
    • short s = 67000 doesn't work because you are exceeding the maximum value that can rapresented with a short
    • short s = (short)67000 works because you are placing a cast so you are explicitly requesting the type checker to ignore the fact that 67000 exceeds the maximum value
    • test(1) doesn't work because it's a method invocation, a narrow conversion is not allowed (int -> short) and 1 is always evaluated as an integer literal by the compiler