Here is my code but I am not getting how int getValue() method accepting char type as return value. How is it working? could any body please explain me how this method is working?
public class CharToInteger {
private static Scanner input;
public static int getValue(char character){
return character;
}
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter a character to get value of it:");
String inputString=(String) input.next();
char inputCharacter=inputString.charAt(0);
System.out.println(getValue(inputCharacter));
}
}
Thanks in advance :)
OK, so first things first:
This is a widening primitive type conversion, so this is legal. You can:
But you CANNOT DO:
Second: what it returns is NOT THE ASCII CODE AT ALL. Java does Unicode.
It just happens that when Java was created, Unicode only defined code points fitting 16 bits; hence
charwas created as a 2 byte, unsigned primitive type (it is the only unsigned primitive type in Java) matching the then-called UCS-2 character coding (a 1 to 1 mapping between the coding and code points).However, afterwards Unicode went "wide" and code points outside the BMP (ie, greater than U+FFFF) appeared; since then UCS-2 became UTF-16, and code points outside the BMP require two
chars for one code point (a leading surrogate and a trailing surrogate; in previous Unicode versions, and in the Java API, those were called resp. high and low surrogate). Acharis therefore now a UTF-16 code unit.It is still true, however, that for code points in the BMP, the
charvalue exactly matches the code point.Now, in order to "fix" your program to accurately display the "character value", ie the code point, for each possible entry, you would do that (Java 8):
This will also handle code points outside the BMP.