String to int without using Integer class in Java

An alternative to converting a String to int is using a custom implementation suing the Character.digit() method.

String number = "12345";
int radix = 10;
int result = 0;
for (int i = 0; i < number.length(); i++) {
    char c = number.charAt(i);
    int digit = Character.digit(c, radix);
    result *= radix;
    result += digit;
}
System.out.print(result);

Output

12345

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>