[java] 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?

This question is related to java integer type-conversion character primitive

The answer is


From the Javadoc for Character#getNumericValue:

If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

The character + does not have a numeric value, so you're getting -1.

Update:

The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.


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.


43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII


public class IntergerParser {

public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}

private static int parseInt(String number){
    char[] numChar = number.toCharArray();
    int intValue = 0;
    int decimal = 1;
    for(int index = numChar.length ; index > 0 ; index --){
        if(index == 1 ){
            if(numChar[index - 1] == '-'){
                return intValue * -1;
            } else if(numChar[index - 1] == '+'){
                return intValue;
            }
        }
        intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
        System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
        decimal = decimal * 10;
    }
    return intValue;
}

As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.

If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:

int value = (int)c.charValue();

Try any one of the below. These should work:

int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to character

Set the maximum character length of a UITextField in Swift Max length UITextField Remove last character from string. Swift language Get nth character of a string in Swift programming language How many characters can you store with 1 byte? How to convert integers to characters in C? Converting characters to integers in Java How to check the first character in a string in Bash or UNIX shell? Invisible characters - ASCII How to delete Certain Characters in a excel 2010 cell

Examples related to primitive

Converting characters to integers in Java What's the difference between primitive and reference types? Java: Integer equals vs. == How to cast Object to boolean? Java equivalent of unsigned long long? Primitive type 'short' - casting in Java Generic type conversion FROM string