This is because in the first case, the return value is a
compile-time constant, and in the second case it is not.
When a value is a compile-time constant, it means the compiler knows at compile time exactly what the value is, so it can check if the value fits in a
short and if it does, then it is allowed to write code like this.
But looking at the second case, you'd say that the compiler should also be able to know that the value is always 500, so this should also be allowed. But it isn't, because there are rules that say when something is a compile-time constant and when it is not, and in the second case the compiler will not regard it as a compile-time constant.
Paragraph 15.28 Constant Expressions of the
Java Language Specification lists what kinds of expressions are regarded as constant expressions. Note that according to these rules, the expression
s in the line
return s; is not a constant expression.
Also relevant is
Paragraph 5.2 Assignment Contexts that explains when a narrowing conversion (such as a conversion from
int to
short) is allowed without a cast.