Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting characters to integers in Java

Can someone please explain to me what is going on here:

char c = '+'; int i = (int)c; System.out.println("i: " + i + " ch: " + Character.getNumericValue(c)); 

This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?

Edit: Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?

Edit2: 43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?

like image 531
JRR Avatar asked Oct 15 '13 18:10

JRR


People also ask

Can we convert character to integer in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do you convert a char to an int?

We can also use the getNumericValue() method of the Character class to convert the char type variable into int type. Here, as we can see the getNumericValue() method returns the numeric value of the character. The character '5' is converted into an integer 5 and the character '9' is converted into an integer 9 .

How do I convert a string to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


1 Answers

Character.getNumericValue(c) 

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

like image 123
Trying Avatar answered Sep 21 '22 00:09

Trying