How can I convert String to Int?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting text to an integer is a small task that often carries real edge cases: empty input, invalid characters, whitespace, or values that do not fit in range. The right answer depends on the language, but the pattern is always the same: parse carefully and decide what should happen when the text is not a valid integer.
Parsing in Common Languages
Different languages use different APIs, but the basic idea is consistent. Here are direct examples in several common languages.
Java
If the string is invalid, Java throws NumberFormatException.
Python
If parsing fails, Python raises ValueError.
JavaScript
Passing the radix 10 is good practice because it makes the intent explicit.
C#
In C#, invalid input throws FormatException or OverflowException depending on the failure.
Prefer Safe Parsing When Input Is Untrusted
If the text comes from a user, file, or network request, exception-free parsing is often nicer than a try-catch around every input.
Example in Java:
Example in C# using TryParse:
That style is often better for validation-heavy code.
Whitespace, Signs, and Bases
Parsing can also involve rules beyond ordinary decimal numbers:
- leading and trailing whitespace may need trimming
- '
-42is valid in most integer parsers' - binary or hexadecimal text may need an explicit base
Example in Java for hexadecimal:
So if your text is not plain base-10 input, use the API that lets you specify the radix clearly.
Do Not Confuse Parsing with Casting
This is a common conceptual mistake. A cast changes how the compiler interprets a value that is already numeric. Parsing converts text into a numeric value. You cannot cast "123" to an integer in the same way you cast 3.14 to 3.
That distinction matters because parsing can fail due to content, while casting fails due to type rules.
Common Pitfalls
- Using parsing APIs on untrusted input without validation or error handling.
- Forgetting to trim whitespace when input comes from forms or files.
- Ignoring overflow cases where the digits are valid but the number is too large.
- Assuming parsing and casting are the same operation.
- Forgetting to specify a radix when the input is not base 10.
Summary
- Converting text to an integer means parsing, not casting.
- Every language has a direct parse function such as
Integer.parseInt,int(),parseInt, orint.Parse. - For untrusted input, safe parsing patterns are usually better than unchecked exceptions.
- Trim input and handle invalid or out-of-range values explicitly.
- Use radix-aware parsing when the input is hexadecimal, binary, or another non-decimal format.

