Java: Why can’t I cast int to Long

I think the question was not about casting primitives and wrappers in general.
The question was about difference between casting int to java.lang.Long and int to java.lang.Short for example.

JLS:
“In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
  • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
    • Byte and the value of the constant expression is representable in the type byte.
    • Short and the value of the constant expression is representable in the type short.
    • Character and the value of the constant expression is representable in the type char”.

So all <=32bit primitives can be casted easily and long (64bit) requires special casting.
It seems illogically.

All illogical things as usual has explanation in backward compability or historical evolution in java.
E.g. classes Integer and Long exist in java since version 1.0. Classes Short and Byte exist in java since 1.1.
That is at the start point integral number can be two types: integer or long. So I think there are different casting rules for these two types of numbers. And then short and byte were added.
I suppose short and byte can have 32-bit implementation in concrete JVMs.

Leave a Comment