Usually this is done like this:

  • init result with 0
  • for each character in string do this
    • result = result * 10
    • get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
    • add the digit to the result
  • return result

Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).

Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):

Copydigit = ord(char) - ord('0')

For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:

Copydigit = ord(char) - ord('0')
if digit > 9 then digit -= 7

Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.

One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.

Answer from rslite on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ integer-valueof-vs-integer-parseint-with-examples
Integer.valueOf() vs Integer.parseInt() with Examples - GeeksforGeeks
July 11, 2025 - It only accepts String as a parameter and on passing values of any other data type, it produces an error due to incompatible types. There are two variants of this method: ... // Java program to demonstrate working parseInt() public class GFG { public static void main(String args[]) { int decimalExample = Integer.parseInt("20"); int signedPositiveExample = Integer.parseInt("+20"); int signedNegativeExample = Integer.parseInt("-20"); int radixExample = Integer.parseInt("20", 16); int stringExample = Integer.parseInt("geeks", 29); System.out.println(decimalExample); System.out.println(signedPositiveExample); System.out.println(signedNegativeExample); System.out.println(radixExample); System.out.println(stringExample); } }
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ home โ€บ java โ€บ java integer parsing
Java Integer Parsing
September 1, 2008 - ... parseInt(int i) โˆ’ This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
Discussions

java - How does Integer.parseInt(string) actually work? - Stack Overflow
Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Good way to encapsulate Integer.parseInt() - Stack Overflow
If anything, I'm tempted to use Integer.parseInt and let autoboxing take care of it, to take advantage of the cache for small values. 2009-09-28T18:33:56.467Z+00:00 ... @Vlasec And not just Optional, but specialized versions for primitives, like OptionalInt. 2018-07-19T03:38:18.797Z+00:00 ... @sf_jeff: IMO, in idiomatic Java ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Integer.parseInt and nextInt()
There is a big difference between the two, so big that they actually have nothing to do with each other. Integer.parseInt works on a String. That String can come from anywhere. It is not limited to the Scanner class. Scanner.nextInt is a method of the Scanner class that waits for an int on the input stream of the Scanner. If it sees a valid integer, it takes it and returns it as an int. If it sees something different to an integer, it throws an exception. The caveat with nextInt or nextDouble is that a possible line break (i.e. Enter) is left in the input buffer. In fact, the nextInt method internally uses Integer.parseInt to produce the int value. Which one do real programmers in the real world use most? They use both, depending on the situation. As I've said above, the two methods are actually not related to each other. More on reddit.com
๐ŸŒ r/learnjava
10
5
April 5, 2015
Integer.valueOf() and parseint()
Integer.parseInt() returns a primitive. valueOf() returns an Integer object. Call the one that matches the return type you need and avoid autoboxing/unboxing. More on reddit.com
๐ŸŒ r/learnjava
5
2
September 14, 2023
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ lang โ€บ Integer.html
Integer (Java Platform SE 8 )
October 20, 2025 - The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Top answer
1 of 8
47

Usually this is done like this:

  • init result with 0
  • for each character in string do this
    • result = result * 10
    • get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
    • add the digit to the result
  • return result

Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).

Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):

Copydigit = ord(char) - ord('0')

For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:

Copydigit = ord(char) - ord('0')
if digit > 9 then digit -= 7

Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.

One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.

2 of 8
28

The source code of the Java API is freely available. Here's the parseInt() method. It's rather long because it has to handle a lot of exceptional and corner cases.

Copypublic static int parseInt(String s, int radix) throws NumberFormatException {
    if (s == null) {
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {
        throw new NumberFormatException("radix " + radix +
            " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {
        throw new NumberFormatException("radix " + radix +
            " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, max = s.length();
    int limit;
    int multmin;
    int digit;

    if (max > 0) {
        if (s.charAt(0) == '-') {
            negative = true;
            limit = Integer.MIN_VALUE;
            i++;
        } else {
            limit = -Integer.MAX_VALUE;
        }
        multmin = limit / radix;
        if (i < max) {
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            } else {
                result = -digit;
            }
        }
        while (i < max) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    if (negative) {
        if (i > 1) {
            return result;
        } else { /* Only got "-" */
            throw NumberFormatException.forInputString(s);
        }
    } else {
        return -result;
    }
}
๐ŸŒ
Global Tech Council
globaltechcouncil.org โ€บ home โ€บ what is parseint in java?
What is parseInt in Java? - Global Tech Council
August 22, 2025 - Hereโ€™s are some examples of parseInt in Java: The most common use of parseInt() is to convert a string that represents a decimal number into an integer.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ api โ€บ java.lang.integer.parseint
Integer.ParseInt Method (Java.Lang) | Microsoft Learn
[<Android.Runtime.Register("parseInt", "(Ljava/lang/String;I)I", "")>] static member ParseInt : string * int -> int ... Parses the string argument as a signed integer in the radix specified by the second argument.
Find elsewhere
Top answer
1 of 16
161

You could return an Integer instead of an int, returning null on parse failure.

It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.

EDIT: Code for such a method:

public static Integer tryParse(String text) {
  try {
    return Integer.parseInt(text);
  } catch (NumberFormatException e) {
    return null;
  }
}

Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.

Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.

2 of 16
41

What behaviour do you expect when it's not a number?

If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:

public static int parseWithDefault(String number, int defaultVal) {
  try {
    return Integer.parseInt(number);
  } catch (NumberFormatException e) {
    return defaultVal;
  }
}

Similar methods can be written for different default behaviour when the input can't be parsed.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ integer.parseint and nextint()
r/learnjava on Reddit: Integer.parseInt and nextInt()
April 5, 2015 -

I dont fully understand the difference between the two. They do exaxtly the same thing. Im assuming with Integer.parseInt(x.nextLine()) it can detect both a string and an Int and nextInt only can detect an Int. Is this right? Or are they bothe the same. Which one do real programmers in the real world use most? Thank you guys!

Top answer
1 of 2
2
There is a big difference between the two, so big that they actually have nothing to do with each other. Integer.parseInt works on a String. That String can come from anywhere. It is not limited to the Scanner class. Scanner.nextInt is a method of the Scanner class that waits for an int on the input stream of the Scanner. If it sees a valid integer, it takes it and returns it as an int. If it sees something different to an integer, it throws an exception. The caveat with nextInt or nextDouble is that a possible line break (i.e. Enter) is left in the input buffer. In fact, the nextInt method internally uses Integer.parseInt to produce the int value. Which one do real programmers in the real world use most? They use both, depending on the situation. As I've said above, the two methods are actually not related to each other.
2 of 2
2
The methods are similar in that Scanner.nextInt() contains a call to Integer.parseInt() but, the Scanner.nextInt() contains some extra code for handling the caches and other scanner specific issues. Source code for Scanner.nextInt() public int nextInt(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof Integer) && this.radix == radix) { int val = ((Integer)typeCache).intValue(); useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next int try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return Integer.parseInt(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } }
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 615414 โ€บ java โ€บ choosing-Integer-decode-String-str
Why choosing to use Integer.decode(String str) over ...
Well, if this helps you decide... in the implementation, the decode() method calls the parseInt() method. The decode() method, decodes the 0x # etc., and then calls parseInt() with the decoded radix. Henry ยท Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ parseint-java
parseInt() Java Method: From Strings to Integers
February 26, 2024 - In this comprehensive guide, weโ€™ve journeyed through the world of parseInt in Java, a powerful tool for converting strings to integers.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java numbers โ€บ difference between parseint() and valueof() in java
Difference Between parseInt() and valueOf() in Java | Baeldung
January 8, 2024 - The first variant of parseInt() accepts a String as a parameter and returns the primitive data type int. It throws NumberFormatException when it cannot convert the String to an integer.
๐ŸŒ
H2K Infosys
h2kinfosys.com โ€บ blog โ€บ introduction to parseint in java
Introduction to ParseInt in Java
September 24, 2024 - The parseInt function of the Integer class receives the string โ€œ123โ€ as an input in this example, and it transforms the string into the integer value 123 and stores it in the number variable.
๐ŸŒ
Codekru
codekru.com โ€บ home โ€บ integer.parseint() method in java with examples
Integer.parseInt() method in Java with Examples - Codekru
December 3, 2022 - public class Codekru { public static void main(String[] args) { String s1 = "A20"; System.out.println("int value representing s1 with radix 16: " + Integer.parseInt(s1,16)); } } ... This method was introduced in Java 9.
๐ŸŒ
Quora
quora.com โ€บ How-does-Integer-parseInt-work-in-Java
How does Integer.parseInt() work in Java? - Quora
Answer (1 of 4): Usually this is done like this: * init result with 0 * for each character in string do thisresult = result * 10get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)add the digit to the result * retur...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ parseInt
parseInt() - JavaScript | MDN
The description below explains in more detail what happens when radix is not provided. An integer parsed from the given string, or NaN when ยท the radix as a 32-bit integer is smaller than 2 or bigger than 36, or ยท the first non-whitespace character cannot be converted to a number. Note: JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. parseInt() and parseFloat() only differ in their parsing behavior, but not necessarily their return values.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_parseint.asp
W3Schools.com
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.
๐ŸŒ
Study.com
study.com โ€บ courses โ€บ business courses โ€บ business 104: information systems and computer applications
How to Convert String to Int in Java - ParseInt Method - Lesson | Study.com
January 9, 2023 - String myString = newString("hello"); int makeNumber = Integer.parseInt(myString); System.out.println(makeNumber); In order to catch the exceptions, place the parseInt function within a try and catch block. The code you want to execute is inside the try statement. After the catch statement, you can display an error should the conversion fail. Since we're trying to convert a non-numeric number to numeric, the exception will be a NumberFormatException in the Java compiler.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ integer.valueof() and parseint()
r/learnjava on Reddit: Integer.valueOf() and parseint()
September 14, 2023 -

Hello, i have started learning java recently by mooc. But during this course, it uses Integer.valueOf while taking integer inputs, I use same way but whenever i do it intellij suggests me parseint(). And I wonder if it is better to use parseint?

Top answer
1 of 3
9
Integer.parseInt() returns a primitive. valueOf() returns an Integer object. Call the one that matches the return type you need and avoid autoboxing/unboxing.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-java-integer-parseint-method-117728
Java parseInt(String, int) | Integer Parsing Tutorial | LabEx
Learn how to use the Java parseInt(String, int) method to parse a string value as a signed decimal Integer object in a specified integer radix value.