Integer.parseInt() is a static method in Java's Integer class used to convert a string representation of an integer into a primitive int value. It is part of the java.lang package and has been available since Java 1.0.
Key Features:
Single Parameter (String s): Parses the string as a signed decimal integer (base 10).
Example:Integer.parseInt("123")returns123.
If the string is invalid (e.g.,"abc","", or"123abc"), it throws a NumberFormatException.Two Parameters (String s, int radix): Parses the string using a specified number base (radix).
Example:Integer.parseInt("101", 2)returns5(binary to decimal).
Valid radix values range from 2 to 36.
If radix is invalid, it throwsNumberFormatException.Advanced Version:
Integer.parseInt(CharSequence s, int beginIndex, int endIndex, int radix)allows parsing a substring by specifying start and end indices.
Common Issues & Best Practices:
NumberFormatException: Occurs with null, empty strings, invalid characters, or non-numeric content.
Whitespace: Leading/trailing spaces are ignored (e.g.,
" 123 "→123).Use
trim(): Always clean input strings to avoid unexpected errors.Validation: Wrap calls in
try-catchblocks to handle parsing failures gracefully.
Performance & Usage:
Returns a primitive
int, making it faster thanInteger.valueOf()for simple conversions.Use
Integer.valueOf()when you need anIntegerobject (e.g., for collections), as it supports caching for values in the range -128 to 127.
✅ Best Practice: Always validate input strings before parsing, and use
try-catchfor robust error handling.
parseInt is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
parseInt is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
I invite you to look at the source code of the parseInt function. Your naïve function is faster, but it also does way less. Edge cases, such as the number being to large to fit into an int or not even being a number at all, will produce undetectable bogus results with your simple function.
It is better to just trust that the language designers have done their job and have produced a reasonably fast implementation of parsing integers. Real optimization is probably elsewhere.
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?
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):
digit = 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:
digit = 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.
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.
public 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;
}
}