Autoboxed when assigned integer or character for the Character Wrapper

127 views Asked by At

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;
3

There are 3 answers

2
Naman Gala On BEST ANSWER

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

2
Sharon Ben Asher On

3 is not necessarily an int. it is short type. Both char and short are 16 bit in length

1
Sashi Kant On

It is the ASCII value assigned to the character.

In the first case

Character character1 = 'a';

The character1 is directly assigned a character value.

But in your second statement:

Character character2 = 3;

character2 is assigned the ASCII value of 3 which is ?