Java example

How to convert a string to an int in Java

7 min read Updated Sep 2026 Runs in an isolated runtime
Quick answer

Use Integer.parseInt(text): Integer.parseInt("42") returns the int 42. It throws NumberFormatException for anything that isn't a whole int, including letters, decimals, blank strings, surrounding spaces and values past 2147483647, so wrap it in try/catch when the text comes from a user. Use Integer.valueOf(text) when you need an Integer object instead.

Java won't cast a String to an int: (int) "42" doesn't compile, because a string is an object, not a number. Parsing lives in the wrapper classes, and Integer.parseInt is strict on purpose. It reads an optional sign and digits, the whole string and nothing else, and throws the moment anything else shows up. That makes the real questions the ones around it: primitive or boxed, what to do on bad input, how to check a string before parsing, and what to use when the number doesn't fit in 32 bits. Each example runs on this page: hit Run, then edit the code and run it again.

1Integer.parseIntRecommended

Integer.parseInt(s) returns a primitive int you can do arithmetic with. A leading - or + is accepted, and leading zeros are just more decimal digits. What it does not do is trim: a space or a trailing newline from a file or a console read is an error, so call strip() first (Java 11+; use trim() on older versions). The two-argument form, parseInt(s, radix), reads any base from 2 to 36.

Main.java

Output

Prints 50, then 428. That second line is the bug the conversion exists to prevent: + with a String on either side concatenates. The sign and zero lines print -17, 5 and 7, so "007" is plain decimal here, not octal. The stripped line prints 42, and the radix lines print 255, -10 and 1295. With radix 16, leave off the 0x prefix: parseInt("0xff", 16) throws. Integer.decode is the method that reads prefixes (see the FAQ).

2parseInt vs valueOf: int or Integer

The two methods parse exactly the same text and throw the same exception. The difference is the return type: parseInt gives a primitive int, and valueOf gives an Integer object, which is what collections, generics and nullable fields need. Autoboxing converts between the two for you, so the choice rarely changes what compiles. It does change what == means, because valueOf hands back cached objects for -128 to 127 and a new object outside that range.

Main.java

Output

Prints 84, since the Integer unboxes for the addition, and [7, 8]. The comparison lines are true, false, true, true: == on two Integer objects compares identity, so it only looks right while the values are small enough to be cached. Compare boxed values with equals, or compare the ints, the same rule as comparing strings. The last line shows the other cost of boxing: an Integer can be null, and unboxing one throws. Don't use new Integer("42"): that constructor has been deprecated since Java 9 and is marked for removal.

3Handle NumberFormatException

Anything parseInt can't read throws NumberFormatException. It is an unchecked exception, so the compiler won't remind you to catch it, and an uncaught one ends the program with a stack trace. For user input, files and query parameters, catch it close to the parse. A small helper that returns an OptionalInt keeps the try/catch in one place and lets each caller pick its own fallback.

Main.java

Output

The loop prints 42, then one message per bad input: For input string: " 42" for the leading space, and the same shape for "", "abc", "3.5", "1,234" and "2147483648". That last one is a valid number, just one more than Integer.MAX_VALUE, and the message doesn't tell you so. A null gives Cannot parse null string, and it is a NumberFormatException too, not a NullPointerException. The helper prints OptionalInt[42] (it strips first), OptionalInt.empty, 0 from orElse, and false. Guava's Ints.tryParse and Apache Commons' NumberUtils.toInt(s, 0) are ready-made versions of the same idea.

4Check if a string is numeric

Sometimes you want a yes or no before, or instead of, catching an exception, for example to validate a form field or to skip a mostly-junk column without paying for thousands of exceptions. The usual answers are a regex and a Character.isDigit loop. The grid below runs both next to parseInt itself so you can see where they disagree with the parser.

Main.java

Output

The regex matches the parser on every row but the last: "99999999999" is all digits, and it still doesn't fit in an int. The digits check is worse. It rejects "-7" and "+5", and it accepts "४२", because Character.isDigit is true for every Unicode digit. parseInt accepts those as well, which is why the next line prints 43, while the regex's \d means ASCII 0 to 9 only. Apache Commons' StringUtils.isNumeric behaves like the digits column. So use a pre-check to reject junk, then still parse inside a try, or cap the regex at 9 digits, which always fit. For decimals, Double.parseDouble is looser than it looks: it prints 3.5, 7.0 (it trims whitespace, unlike parseInt), 1000.0, NaN, Infinity, 2.0 for "2f" and 16.0 for the hex float "0x1p4". If "numeric" means plain decimal text, check with a regex such as [+-]?\d+(\.\d+)?.

5Too big for an int, or a decimal string

An int holds up to 2147483647. For bigger whole numbers, such as IDs, byte counts and timestamps in milliseconds, parse with Long.parseLong, which follows the same rules up to about 9.2 × 1018, or with new BigInteger(s), which has no fixed limit. If you need an int at the end, narrow with Math.toIntExact rather than a cast. A string with a decimal point is a different job: parse it as a number first, then decide how it becomes whole.

Main.java

Output

Prints 2147483647 and 9000000000. Then the cast prints 410065408: (int) keeps the low 32 bits and says nothing, while Math.toIntExact throws ArithmeticException: integer overflow. The BigInteger adds exactly, 123456789012345678901234567891, and intValueExact refuses with BigInteger out of int range. The decimal lines are 3 (the cast truncates), 4 (Math.round) and -3, since truncation goes toward zero. BigDecimal.intValueExact converts "42.00" to 42 and throws Rounding necessary for "3.99", which is what you want when a fraction means the input is wrong. For other rounding rules, see rounding to 2 decimal places.

6Which should you use?

MethodReturnsOn bad inputBest for
Integer.parseInt(s)intThrows NumberFormatExceptionAlmost everything: the default
Integer.valueOf(s)Integer (cached for -128 to 127)Throws NumberFormatExceptionCollections, generics, nullable fields
tryParseInt(s) helperOptionalIntEmpty; the caller picks a fallbackUser input, files, query parameters
Pattern [+-]?\d+booleanfalse, but misses overflowCheap pre-check before parsing
Integer.decode(s)IntegerThrows NumberFormatExceptionText with 0x, # or octal 0 prefixes
Long.parseLong(s)longThrows NumberFormatExceptionValues past 2147483647
new BigInteger(s)BigIntegerThrows NumberFormatExceptionIntegers of any size

Frequently asked questions

What is the difference between Integer.parseInt and Integer.valueOf?

Integer.parseInt(s) returns a primitive int; Integer.valueOf(s) returns an Integer object. They accept the same text and both throw NumberFormatException on bad input. valueOf returns cached objects for -128 to 127, so it is the right choice when you need an object, for a List<Integer> or a nullable field. For arithmetic, use parseInt and skip the boxing.

Why does Integer.valueOf("128") == Integer.valueOf("128") return false?

== on two Integer objects checks whether they are the same object, not whether they hold the same number. Integer.valueOf caches the values -128 to 127, so Integer.valueOf("127") == Integer.valueOf("127") is true by coincidence, while 128 creates two separate objects and gives false. Use a.equals(b), or compare ints from parseInt, which gives true.

How do I check if a String is numeric in Java?

The most reliable check is to try the parse: call Integer.parseInt(s) in a try block and return false from the catch (NumberFormatException e). A precompiled regex such as [+-]?\d+ is cheaper when most input is bad, but it says yes to "99999999999", which is too big for an int, so keep the try/catch as the final word or limit the regex to 9 digits. Avoid Character.isDigit loops: they reject "-7".

Why does Integer.parseInt throw NumberFormatException for " 42" or "42\n"?

parseInt does not skip whitespace, so any space, tab or trailing newline makes the whole string invalid: For input string: " 42". Strip the text first with Integer.parseInt(s.strip()). strip() (Java 11+) removes all Unicode whitespace, such as the em space U+2003, while the older trim() only removes characters up to U+0020.

How do I convert a hex string, or one with a 0x prefix, to an int?

Pass the radix and leave the prefix off: Integer.parseInt("ff", 16) is 255. Integer.parseInt("0xff", 16) throws For input string: "0xff" under radix 16. If the prefix is part of the text, use Integer.decode: Integer.decode("0x1F") is 31 and Integer.decode("#FF") is 255. Careful with decode on user input, though, because a leading zero means octal: Integer.decode("010") is 8.

How do I parse a number with commas, like "1,234,567"?

Remove the separators first: Integer.parseInt("1,234,567".replace(",", "")) gives 1234567. NumberFormat.getIntegerInstance(Locale.US).parse("1,234,567") also returns 1234567 and understands locale formats, but it stops at the first character it cannot read and returns what it has, so parse("12abc") gives 12 without an error.

Run it yourself

Open any of these in the full Java editor to tweak, run and share.

Java playground