Search code examples
javaautoboxing

Autoboxed when assigned integer or character for the Character Wrapper


why we can assign both int value and a char value to Character Wrapper type. Autoboxing means boxing for the corresponding wrapper but Character is not the corresponding wrapper of int. It is Integer

why both of these statements are possible

Character character = 'a';
Character character2 = 3;

Solution

  • It is treated as an ASCII value, if you assign int value to Character.

    Below 4 approach result in same output.

    Character character2 = 'e';
    

    Character character2 = 101;
    

    int i = 101;
    Character character2 = (char)i; // casting int to char i.e. treat it as ASCII value
    

    Character character2 = (char)101;  
    

    System.out.println(character2); // Prints e
    

    Note: You can refer this ASCII Table