Question
How can I convert a String value to an int in Java?
For example, how do I convert:
"1234" // String
into:
1234 // int
What is the correct and safe way to do this in Java?
Short Answer
By the end of this page, you will understand how to convert a numeric String into an int in Java, which methods are commonly used, what happens when the text is not a valid number, and how to handle conversion errors safely in real programs.
Concept
In Java, a String is text, while an int is a numeric primitive type. Even if a string looks like a number, such as "1234", Java still treats it as text until you explicitly convert it.
The most common way to do this conversion is with:
Integer.parseInt("1234")
This tells Java to read the characters in the string and turn them into an integer value.
Why this matters:
- User input often arrives as text
- Data from files, APIs, and forms is usually read as strings
- You cannot do numeric calculations correctly until the value is converted
For example:
String a = "10";
String b = "20";
System.out.println(a + b); // 1020
That joins text together. But after conversion:
int a = Integer.parseInt("10");
int b = Integer.parseInt("20");
System.out.println(a + b);
Mental Model
Think of a String as a label with characters printed on it, and an int as an actual number stored in a calculator.
"1234"is just text on the label1234is a number the calculator can use
Integer.parseInt() is like reading the label and typing the value into the calculator.
If the label says something invalid like "12ab", the calculator operator stops and says, "This is not a valid whole number." In Java, that is a NumberFormatException.
Syntax and Examples
The main syntax is:
int number = Integer.parseInt(stringValue);
Basic example
String text = "1234";
int number = Integer.parseInt(text);
System.out.println(number); // 1234
System.out.println(number + 1); // 1235
Explanation:
textstores the value as aStringInteger.parseInt(text)converts it to anint- The result can now be used in math operations
Example with invalid input handling
String text = "12a4";
try {
int number = Integer.parseInt(text);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println( + text);
}
Step by Step Execution
Consider this code:
String text = "42";
int number = Integer.parseInt(text);
System.out.println(number * 2);
Step by step:
-
String text = "42";- A string variable named
textis created - Its value is the characters
4and2
- A string variable named
-
int number = Integer.parseInt(text);- Java reads the contents of
text - It checks whether the string represents a valid integer
- Since
"42"is valid, Java converts it to the numeric value42 - That numeric value is stored in
number
- Java reads the contents of
-
System.out.println(number * 2);- Java multiplies the integer
42by
- Java multiplies the integer
Real World Use Cases
String-to-int conversion is used constantly in Java programs.
Reading user input
String ageText = "25";
int age = Integer.parseInt(ageText);
Useful when reading values from forms, console input, or GUI fields.
Processing CSV or file data
A file may store numbers as text:
String quantityText = "12";
int quantity = Integer.parseInt(quantityText);
This is common when importing reports or product data.
Query parameters and API input
Web applications often receive values like page numbers, IDs, or limits as strings.
String pageText = "3";
int page = Integer.parseInt(pageText);
Configuration values
Environment variables or properties files often store everything as text.
Real Codebase Usage
In real projects, developers rarely assume input is always valid. Instead, they combine conversion with validation and error handling.
Guard clause pattern
public static int parseAge(String input) {
if (input == null || input.isBlank()) {
throw new IllegalArgumentException("Age is required");
}
return Integer.parseInt(input);
}
This rejects empty input early.
Safe parsing with fallback
public static int parseOrDefault(String input, int defaultValue) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
return defaultValue;
}
}
This is useful for configuration and optional inputs.
Validation before business logic
String quantityText = request.getParameter("quantity");
Integer.parseInt(quantityText);
(quantity < ) {
();
}
Common Mistakes
1. Using a cast instead of parsing
This does not convert text to a number:
String text = "123";
// int number = (int) text; // invalid
Why it fails:
- Casting works between compatible types
Stringandintare fundamentally different types
Use this instead:
int number = Integer.parseInt(text);
2. Forgetting that invalid text causes an exception
Broken example:
String text = "12abc";
int number = Integer.parseInt(text); // throws NumberFormatException
Avoid this by handling bad input:
try {
int number = Integer.parseInt(text);
} (NumberFormatException e) {
System.out.println();
}
Comparisons
| Approach | Returns | Best use | Notes |
|---|---|---|---|
Integer.parseInt("123") | int | When you need a primitive integer | Most common choice |
Integer.valueOf("123") | Integer | When you need an Integer object | Can be auto-unboxed to int |
new Integer("123") | Integer | Avoid | Old style and unnecessary |
Double.parseDouble("123.5") |
Cheat Sheet
Convert String to int
int number = Integer.parseInt(text);
Safe version
try {
int number = Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid number");
}
Useful rules
"123"works"-123"works"12.5"does not work forint"abc"does not worknullmust be handled carefully- Spaces may need
trim()
Related methods
Integer.parseInt("123"); // returns int
Integer.valueOf("123");
Double.parseDouble();
Long.parseLong();
FAQ
What is the easiest way to convert a String to an int in Java?
Use:
int number = Integer.parseInt("1234");
What happens if the String is not a valid number?
Java throws a NumberFormatException. You can handle it with try-catch.
Can I convert "12.5" to an int with parseInt?
No. Integer.parseInt() only works for whole numbers. For decimals, use Double.parseDouble().
Should I use Integer.parseInt() or Integer.valueOf()?
Use Integer.parseInt() when you want a primitive int. Use Integer.valueOf() when you need an Integer object.
Does Integer.parseInt() work with negative numbers?
Mini Project
Description
Build a small Java program that reads a list of numeric strings, converts them to integers, and prints their sum. This demonstrates basic parsing, looping, and safe error handling for invalid input.
Goal
Create a program that converts valid numeric strings to int values and skips invalid entries without crashing.
Requirements
- Store several values as strings in an array
- Convert each valid string to an integer
- Ignore or report invalid numeric strings
- Calculate and print the total sum
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.