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
In Java, converting a String to an int is usually done with Integer.parseInt. That sounds simple, but real code also has to deal with invalid input, whitespace, and numbers that may not fit inside the int range. A good solution therefore combines parsing with validation and clear error handling.
The Standard Java Conversion
The most direct conversion uses Integer.parseInt.
This works when the string is a valid base-10 integer inside the int range.
If the string is not valid, Java throws NumberFormatException.
Handle Invalid Input Safely
In production code, you usually should not assume the text is always valid.
This is the standard pattern when the input comes from a user, a file, or an API.
Trim Whitespace Before Parsing
Input often contains spaces around the number. parseInt does not automatically accept arbitrary surrounding whitespace in the way many developers expect, so trimming is a good habit.
If you skip trim(), seemingly valid input may fail.
parseInt Versus valueOf
Java also provides Integer.valueOf.
The main difference is that parseInt returns a primitive int, while valueOf returns an Integer object. If you only need a primitive, parseInt is the clearer choice.
Other Bases And Numeric Formats
If the string is in another base, pass the radix explicitly.
This prints 10 because the input is interpreted as binary.
That is useful when parsing hexadecimal, binary, or other fixed-base input formats.
Build A Helper When Parsing Happens Often
If your code parses user input frequently, a helper method can make the call sites cleaner.
Java does not have a built-in TryParse method like C#, so helpers like this are common when exceptions are not convenient at the call site.
Common Pitfalls
The most common mistake is assuming the string is always valid. Any non-numeric character, bad sign placement, or overflow will trigger NumberFormatException.
Another issue is forgetting to trim whitespace before parsing user input.
It is also easy to parse into the wrong numeric type. If the number may exceed int, use Long.parseLong or new BigInteger(...) instead.
Finally, do not confuse character codes with numeric parsing. Converting a string digit such as "7" to 7 is not the same as reading the Unicode value of the character.
Summary
- Use
Integer.parseIntfor normal Java string-to-intconversion. - Wrap parsing in
try/catchwhen input may be invalid. - Trim input first if it may contain surrounding whitespace.
- Use
valueOfonly when you specifically want anIntegerobject. - Choose a larger numeric type if the input may exceed the
intrange.

