Convert String to int in Java
Problem
Text such as "2048" is a sequence of characters, not a number — it has to be parsed before you can do arithmetic with it.
Given several strings, convert each valid one to an int and report the ones that cannot be converted.
Java Program
public class StringToInt {
public static void main(String[] args) {
String[] inputs = {"2048", "-75", "12ab"};
for (String text : inputs) {
try {
int value = Integer.parseInt(text); // throws if the text isn't a whole number
System.out.println("\"" + text + "\" -> " + value + " (doubled: " + value * 2 + ")");
} catch (NumberFormatException e) {
System.out.println("\"" + text + "\" is not a valid integer");
}
}
Integer boxed = Integer.valueOf("2048"); // same parsing, but returns an Integer object
System.out.println("valueOf gives an Integer: " + boxed);
}
}Output
Core Logic
Integer.parseInt does the conversion, and wrapping it in try-catch turns bad input into a message instead of a crash.
- 1
Integer.parseInt(text)returns a primitiveintfor valid text, including a leading minus sign. - 2The doubled value printed next to it proves the result is a real number, not text.
- 3Text such as
"12ab"makesparseIntthrow aNumberFormatException, which thecatchblock reports. - 4
Integer.valueOfparses the same way but returns anIntegerobject.
"-75" parses to -75, and doubling it gives -150.Key Point: Use parseInt when you need a primitive for arithmetic, and valueOf when you need an object, for example to store in a List<Integer>.
Key Concepts
Approach 2: Manual Parsing (Digit by Digit)
public class StringToIntManual {
public static void main(String[] args) {
System.out.println(parse("2048"));
System.out.println(parse("-75"));
System.out.println(parse("+309"));
}
static int parse(String text) {
int i = 0;
boolean negative = false;
if (text.charAt(0) == '-' || text.charAt(0) == '+') {
negative = text.charAt(0) == '-';
i = 1; // skip the sign
}
int result = 0;
for (; i < text.length(); i++) {
char c = text.charAt(i);
if (c < '0' || c > '9') {
throw new NumberFormatException("Bad digit: " + c);
}
result = result * 10 + (c - '0'); // shift left one decimal place, add the new digit
}
return negative ? -result : result;
}
}
Output
Core Logic
Building the number one digit at a time — multiply by 10, add the new digit — is the classic interview version of parseInt.
- 1An optional leading
+or-is noted and skipped. - 2Each remaining character is checked to be a digit; anything else throws a
NumberFormatException. - 3
result * 10 + (c - '0')appends the digit to the number built so far. - 4The sign is applied at the end.
"2048": 2 → 20 → 204 → 2048.Key Point: A production-grade version also guards against overflow — values beyond Integer.MAX_VALUE wrap around silently in this simple loop.
Why: Each of the n characters is examined once, with a single running total.
Key Concepts
Interview Questions
What's the difference between parseInt and valueOf?
Integer.parseInt returns a primitive int. Integer.valueOf returns an Integer object and may reuse cached objects for small values.
How do you parse a number with spaces around it?
Call trim() first. Integer.parseInt(" 42") throws a NumberFormatException because of the space.