String to int and int to String Conversion in Java
Fast recall
Quick revision
Core answer
Integer.parseInt(text) and to an Integer with Integer.valueOf(text); invalid syntax or an out-of-range value throws NumberFormatException. Convert an int to text with Integer.toString(value) or String.valueOf(value). These are parsing and formatting operations, not casts.Practical Java knowledge — type conversion is done in almost every real application
Using Integer.parseInt on a non-numeric string without try-catch, or casting a String to int directly (which doesn't work)
Distinguish parseInt (returns primitive) vs valueOf (returns Integer object), and mention NumberFormatException handling
Interview-ready guide
Interview answer
I parse a String with Integer.parseInt, which returns a primitive int. If I need the wrapper, I use Integer.valueOf. For example, Integer.parseInt("2A", 16) returns 42. Invalid syntax, embedded or surrounding whitespace, and an out-of-range value can produce NumberFormatException, so an input boundary should validate, map, or propagate that failure according to its contract.
To convert an int back to text, I use Integer.toString(value) or String.valueOf(value). This is not casting: (int) "42" does not compile because no Java conversion interprets that reference as numeric text. Primitive numeric casts and compatible reference casts are separate language conversions; parsing and formatting are library operations.
String to int and int to String Conversion in Java
Direct Answer
Convert text to a primitive integer with Integer.parseInt(text) and to an Integer with Integer.valueOf(text); invalid syntax or an out-of-range value throws NumberFormatException. Convert an int to text with Integer.toString(value) or String.valueOf(value). These are parsing and formatting operations, not casts.
Common Mistakes & Pitfalls
- Trying
(int) "42": parsing text is not a cast. - Assuming whitespace is accepted:
parseIntdoes not trim the input. - Returning zero for every failure: that confuses invalid input with a real zero.
- Ignoring range: a syntactically numeric value can still exceed int bounds.
- Reasoning about stack allocation or guaranteed wrapper allocation: the language specifies values and references, while the JVM chooses storage and optimization.
Check your understanding
Answer these without looking back at the article.
- What exception does Integer.parseInt throw on invalid input?
- What is the difference between Integer.parseInt() and Integer.valueOf()?
- How do you convert a double to a String?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.