Java Programs›Basics & I/O›Convert String to int

Convert String to int in Java

beginner·  Basics & I/O  ·  Type Conversion

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.

Input
"2048", "-75", "12ab"
Output
2048, -75, error for "12ab"

Java Program

Java
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

"2048" -> 2048 (doubled: 4096) "-75" -> -75 (doubled: -150) "12ab" is not a valid integer valueOf gives an Integer: 2048

Core Logic

Integer.parseInt does the conversion, and wrapping it in try-catch turns bad input into a message instead of a crash.

How It Works
  1. 1Integer.parseInt(text) returns a primitive int for valid text, including a leading minus sign.
  2. 2The doubled value printed next to it proves the result is a real number, not text.
  3. 3Text such as "12ab" makes parseInt throw a NumberFormatException, which the catch block reports.
  4. 4Integer.valueOf parses the same way but returns an Integer object.
"-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

Integer.parseInt()Integer.valueOf()try-catchNumberFormatException

Approach 2: Manual Parsing (Digit by Digit)

Java
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

2048 -75 309

Core Logic

Building the number one digit at a time — multiply by 10, add the new digit — is the classic interview version of parseInt.

How It Works
  1. 1An optional leading + or - is noted and skipped.
  2. 2Each remaining character is checked to be a digit; anything else throws a NumberFormatException.
  3. 3result * 10 + (c - '0') appends the digit to the number built so far.
  4. 4The sign is applied at the end.
For "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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each of the n characters is examined once, with a single running total.

Key Concepts

char arithmeticsign handlingHorner's method

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.

Learn the Concept

Related Programs