Search code examples
javawrapperliteralsprimitive

assigning int literal to Long in java


I see no clear rationale for happening this ..

public  class wrappers
{
    public static void main(String []args)
    {
        short s1=32767; // (primitive) works fine without compile error
        short s2=32768;   fails as this is  beyond short's range


        Short s3=32767; //(wrapper) works fine without compile error
        Short s4=32768; fails as this is beyond short's range

        long l1 =34   // (wrapper)works fine (with_in_range)


        Long l2 =34    // fails, without 34L (with_in_range)

    }

I know that when you assign int literal for wrapper classes, valueOf() is called;

while for Short(Wrapper) this seems to work but for Long(wrapper) above assignments in code fail.

Are there any rules governing these wrapper classes' assignments?


Solution

  • To expand on Jon's answer, the rule that allows Short s3=32767 to work is also specified in the JLS. There's a special rule regarding assignment of constant expressions :

    5.2. Assignment Contexts
    ...

    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:

      1. Byte and the value of the constant expression is representable in the type byte.

      2. Short and the value of the constant expression is representable in the type short.

      3. Character and the value of the constant expression is representable in the type char.