'What happens if I assign a character to an int type in Java? [duplicate]

In this piece of code:

public class TestChar {
    public static void main(String[] args) {
        char c = 'A';
        int n = c; 
        System.out.println(n);
    }
}

Why does it print 65? Is it the Unicode value of the character 'A'?



Solution 1:[1]

'A' is the character literal A (Unicode code value 65)

Solution 2:[2]

Yes, it is the UTF-16 Unicode value of ' A'

Solution 3:[3]

The reason it prints 65 instead of A is overloading: the method println is actually a number of different methods, distinguished by the arguments they take. There are these two among others:

println(char) - prints the value as a character

println(int) - prints the value as a number

Internally the representation of the char 'A' and the int 65 is the same. The only difference is that the two types have different storage sizes. However, when you pass them to println the type is used to select which variant of the method to call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rubydesic
Solution 3 k314159