javaautoboxingjava-21

Java autoboxing concept related query


I have been preparing for OCPJP 21 exam. While studying autoboxing, I have a question about below snippet:

class CharacterAutoboxing {

    public static void main(String args[]) {
        Character p = 97;
        System.out.println(p);
        
        Long l = 116L;
        System.out.println(l);
        // p = (int)l.longValue();
        p = (char)(int)l.longValue();
        
        System.out.println(p);
    } // end of main

}

My query is Character p = 97 is allowed by compiler. 97 is int. So int is autoboxed into character.

Then why p = (int)l.longValue(); is not allowed. Compiler is giving exception as int cannot be converted to Character


Solution

  • Constant expression

    My query is Character p = 97 is allowed by compiler. 97 is int. So int is autoboxed into Character.

    If the RHS (right hand side) of an assignment is a constant expression, AND the type is an integral primitive type, AND the value is within the range of the LHS (left hand side) type, THEN value of the RHS can be assigned to the LHS without a cast. Autoboxing is also allowed.

    The expression 97 is a constant expression, and it is in the range of char. Because the expression is constant, the compiler is able to determine that the value is within range, and no lossy conversion will occur.

    The relevant JLS rules are in JLS 5.2 ... starting at "In addition, if the expression is a constant expression ...".

    Not a constant expression

    Then why p = (int)l.longValue(); is not allowed. Compiler is giving exception as int cannot be converted to Character.

    Because the RHS expression is not a constant expression.

    Since it is not, the compiler doesn't know what the value will be, and hence it doesn't know that the assignment cannot result in loss of information.

    Hence, the Java language requires you to "acknowledge" the potentially lossy conversion by using an explicit type cast to char. Autoboxing can then occur.

    Note: the compiler is giving you a compilation error not an exception!