Question

How to Convert a String to an int in Java

javastringtype-conversioninteger

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); // 30

Now Java performs arithmetic instead of string concatenation.

If the string does not contain a valid integer, Java throws a NumberFormatException. That is why safe conversion often includes validation or a try-catch block.

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 label
  • 1234 is 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.

Take Quiz

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:

  • text stores the value as a String
  • Integer.parseInt(text) converts it to an int
  • 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("Invalid integer: " + text);
}

Explanation:

  • If the string is a valid integer, conversion succeeds
  • If not, the catch block runs instead of crashing the program

parseInt vs valueOf

String text = "1234";

int a = Integer.parseInt(text);
int b = Integer.valueOf(text);

System.out.println(a); // 1234
System.out.println(b); // 1234

Integer.valueOf() returns an Integer object, but Java can automatically unbox it to int. For simple conversion to a primitive int, Integer.parseInt() is usually clearer.

Step by Step Execution

Consider this code:

String text = "42";
int number = Integer.parseInt(text);
System.out.println(number * 2);

Step by step:

  1. String text = "42";

    • A string variable named text is created
    • Its value is the characters 4 and 2
  2. 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 value 42
    • That numeric value is stored in number
  3. System.out.println(number * 2);

    • Java multiplies the integer 42 by 2
    • The result 84 is printed

Output:

84

Now look at an invalid case:

String text = "42x";
int number = Integer.parseInt(text);

What happens:

  1. Java reads "42x"
  2. It tries to interpret it as an integer
  3. The character x is not valid in an integer
  4. Java throws NumberFormatException
  5. If you do not handle that exception, the program stops at that point

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.

String timeoutText = "5000";
int timeout = Integer.parseInt(timeoutText);

Performing calculations

If values stay as strings, math will not work correctly. Converting allows:

  • addition
  • subtraction
  • comparisons
  • loops and counters
Take Quiz

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");
int quantity = Integer.parseInt(quantityText);

if (quantity < 1) {
    throw new IllegalArgumentException("Quantity must be positive");
}

Conversion usually happens near the boundary of the system, before the rest of the application uses the value.

Parsing collections of values

String[] parts = {"10", "20", "30"};

for (String part : parts) {
    int value = Integer.parseInt(part);
    System.out.println(value);
}

This appears often in batch processing, CSV import logic, and data transformation code.

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
  • String and int are 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);
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid whole number.");
}

3. Not handling null

Broken example:

String text = null;
int number = Integer.parseInt(text);

This will fail. Check first:

if (text != null) {
    int number = Integer.parseInt(text);
}

4. Expecting decimal numbers to work with int

Broken example:

String text = "12.5";
int number = Integer.parseInt(text); // invalid

If the input may contain decimals, use Double.parseDouble() instead.

5. Ignoring leading or trailing spaces

String text = " 1234 ";
int number = Integer.parseInt(text); // may throw NumberFormatException

Safer version:

int number = Integer.parseInt(text.trim());

6. Confusing Integer with int

Integer a = Integer.valueOf("123");
int b = Integer.parseInt("123");
  • Integer is an object wrapper
  • int is a primitive
  • Both can represent the value, but they are not the same type

Comparisons

ApproachReturnsBest useNotes
Integer.parseInt("123")intWhen you need a primitive integerMost common choice
Integer.valueOf("123")IntegerWhen you need an Integer objectCan be auto-unboxed to int
new Integer("123")IntegerAvoidOld style and unnecessary
Double.parseDouble("123.5")doubleFor decimal numbersNot for whole-number int input

parseInt vs valueOf

int a = Integer.parseInt("7");
Integer b = Integer.valueOf("7");

Use parseInt when:

  • you want an int
  • you are doing calculations
  • you want the clearest primitive conversion

Use valueOf when:

  • you specifically need an Integer object
  • you are working with collections or APIs that expect objects

int vs Integer

TypeKindCan be null?Example
intPrimitiveNoint x = 5;
IntegerObject wrapperYesInteger x = 5;

For most beginner cases, converting a string to an int means using Integer.parseInt().

Take Quiz

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 for int
  • "abc" does not work
  • null must be handled carefully
  • Spaces may need trim()

Related methods

Integer.parseInt("123");   // returns int
Integer.valueOf("123");    // returns Integer
Double.parseDouble("12.5"); // returns double
Long.parseLong("123456");  // returns long

Common exception

NumberFormatException

Thrown when the string is not a valid integer.

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?

Yes.

int n = Integer.parseInt("-42");

Do I need to trim spaces before parsing?

Often yes. If input may contain extra spaces, use:

int n = Integer.parseInt(text.trim());

Can I cast a String to an int in Java?

No. Casting does not convert a string of characters into a numeric value. Use parsing instead.

Take Quiz

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
Take Quiz

Keep learning

Related questions

View more