Question

How to Check if a String Is Numeric in Java

javastringnumeric

Question

In Java, how can you check whether a String contains a numeric value before attempting to parse it?

For example, you may want to validate the string first so that calling methods such as Integer.parseInt() or Double.parseDouble() does not fail unexpectedly.

Short Answer

By the end of this page, you will understand how to check whether a String is numeric in Java, when to use parsing with exception handling versus pattern-based validation, and how to avoid common mistakes with signs, decimals, whitespace, and null values.

Concept

A common Java task is deciding whether text can safely be treated as a number.

A String is just text. Even if it looks like a number, Java does not automatically treat it as one. Before converting it with methods like Integer.parseInt() or Double.parseDouble(), you often need to validate the input.

There are two common ways to check if a string is numeric:

  1. Try parsing it

    • Attempt to convert the string to a number.
    • If parsing succeeds, the string is numeric.
    • If it throws NumberFormatException, it is not numeric.
  2. Check the format first

    • Use logic such as regular expressions or character checks.
    • This is useful when you want stricter rules, such as "digits only".

Why this matters in real programming:

  • User input from forms often arrives as strings.
  • Query parameters and API payloads may contain invalid numeric text.
  • Configuration files may contain missing or malformed values.
  • Validation helps prevent crashes and improves error messages.

An important detail: "numeric" can mean different things depending on the problem.

For example:

  • "123" → integer-like numeric string
  • "-45" → signed integer
  • "3.14" → decimal number
  • "1e3" → scientific notation, valid for Double.parseDouble()
  • " 42 " → may need trimming first
  • "12a" → not numeric

So the correct solution depends on what kind of number you want to accept.

Mental Model

Think of parsing like trying a key in a lock.

  • If the key fits, the string is a valid number for that parser.
  • If it does not fit, Java throws an error.

Think of regex or character checks like inspecting the key before using it.

  • You look at its shape first.
  • This can be faster for simple rules like "digits only".
  • But if the rules get more complex, inspection can become harder than simply trying the lock.

A good beginner rule is:

  • If you want to know whether Java can parse the value, try parsing.
  • If you want a custom definition like "only positive whole numbers", validate the format explicitly.
Take Quiz

Syntax and Examples

The most reliable general-purpose approach in Java is to try parsing the string.

Example: check for an integer

public class Main {
    public static boolean isInteger(String value) {
        if (value == null) {
            return false;
        }

        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(isInteger("123"));   // true
        System.out.println(isInteger("-45"));   // true
        System.out.println(isInteger("3.14"));  // false
        System.out.println(isInteger("abc"));   // false
        System.out.println(isInteger(null));     // false
    }
}

This works because Integer.parseInt() only accepts valid integer strings within the int range.

Example: check for a decimal number

public class Main {
    public static boolean isDouble(String value) {
        if (value == null) {
            return false;
        }

        try {
            Double.parseDouble(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

This accepts values such as:

  • "3.14"
  • "-0.5"
  • "1e3"

Example: digits only

If you want to allow only digits, use a regular expression.

public class Main {
    public static boolean isDigitsOnly(String value) {
        return value != null && value.matches("\\d+");
    }
}

This returns true for "123", but false for:

  • "-123"
  • "3.14"
  • " 123 "

So this is not the same as "any valid number." It means one or more digits only.

Step by Step Execution

Consider this example:

public static boolean isInteger(String value) {
    if (value == null) {
        return false;
    }

    try {
        Integer.parseInt(value);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Now trace isInteger("42"):

  1. The method receives "42".
  2. It checks value == null.
  3. The value is not null, so execution continues.
  4. Inside the try block, Integer.parseInt("42") runs.
  5. Java successfully converts the string to the integer 42.
  6. No exception is thrown.
  7. The method returns true.

Now trace isInteger("4.2"):

  1. The method receives "4.2".
  2. It is not null.
  3. Integer.parseInt("4.2") runs.
  4. Java sees a decimal point, which is not valid for parseInt().
  5. NumberFormatException is thrown.
  6. Control jumps to the catch block.
  7. The method returns false.

Now trace isInteger(null):

  1. The method receives null.
  2. value == null is true.
  3. The method returns false immediately.
  4. Parsing is never attempted.

This pattern is called a guard clause: it exits early for invalid input.

Real World Use Cases

Checking whether a string is numeric appears in many real applications.

Form validation

A user enters their age in a text field. You need to ensure it is a whole number before saving it.

String ageInput = "27";
if (isInteger(ageInput)) {
    int age = Integer.parseInt(ageInput);
}

Reading query parameters in web apps

A URL might contain ?page=3. Since query parameters arrive as strings, you validate before using them.

Importing CSV data

When reading rows from a file, columns such as price, quantity, or score may contain invalid text like N/A or empty strings.

Configuration values

Environment variables and properties files store values as strings. If a timeout or port number should be numeric, validation prevents startup errors.

API request validation

Incoming JSON fields may be strings even when they represent numbers. Validation helps return a clear error instead of a server exception.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just check whether a value is numeric.

Guard clauses

A common pattern is to reject invalid input early.

public int parseUserId(String input) {
    if (input == null || input.isBlank()) {
        throw new IllegalArgumentException("User ID is required");
    }

    try {
        return Integer.parseInt(input);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("User ID must be a valid integer");
    }
}

Validation before business logic

Developers often validate request data before performing database operations, calculations, or service calls.

Trimming input

User input often contains spaces.

String input = " 42 ";
if (isInteger(input.trim())) {
    int value = Integer.parseInt(input.trim());
}

Range validation after parsing

A value can be numeric but still invalid for the business rule.

int age = Integer.parseInt(input);
if (age < 0 || age > 150) {
    throw new IllegalArgumentException("Age out of range");
}

Utility methods

Teams often create small helper methods such as:

  • isInteger(String value)
  • isPositiveInteger(String value)
  • parseIntOrDefault(String value, int defaultValue)

This keeps validation consistent across the codebase.

Common Mistakes

Here are common beginner mistakes when checking numeric strings in Java.

Mistake 1: Assuming digits-only means every numeric value

Broken example:

"-12".matches("\\d+")

This returns false because \d+ does not allow a minus sign.

Use parsing if you want standard Java numeric formats, or write a regex that matches your exact rules.

Mistake 2: Forgetting about null

Broken example:

value.matches("\\d+")

If value is null, this throws NullPointerException.

Safer version:

value != null && value.matches("\\d+")

Mistake 3: Ignoring whitespace

Broken example:

Integer.parseInt(" 42 ");

This throws NumberFormatException because parseInt() does not accept surrounding spaces.

Safer version:

Integer.parseInt(input.trim());

Mistake 4: Using the wrong parser

Broken example:

Integer.parseInt("3.14");

This fails because parseInt() expects an integer, not a decimal.

Use:

Double.parseDouble("3.14");

Mistake 5: Confusing valid numeric format with valid business value

A string may be numeric but still unacceptable.

String ageInput = "999";

This is numeric, but probably not a valid age. Always separate:

  • format validation
  • business rule validation

Mistake 6: Using regex for everything

Regex is useful, but complex numeric formats can become hard to read and maintain. If your goal is "can Java parse this?", parsing is usually clearer.

Comparisons

Here is how common approaches compare.

ApproachBest forAccepts signs/decimals?ProsCons
Integer.parseInt() in try/catchValidating integersSigns yes, decimals noMatches Java parsing rules exactlyOnly for integers, throws exception on failure
Double.parseDouble() in try/catchValidating decimal/scientific notationYesHandles many numeric formatsAccepts formats you may not want, such as scientific notation
value.matches("\\d+")Digits-only inputNoSimple and readable for strict digit checksDoes not allow -, +, decimals, or spaces
Character-by-character checkCustom validation rulesDepends on your codeFull controlMore code to write and test

parseInt() vs regex

  • Use parseInt() when you want to know whether Java can convert the string to an int.
  • Use regex when you want a stricter input rule like "only digits, no sign, no spaces".

Integer.parseInt() vs Long.parseLong()

Both validate integer strings, but they support different ranges.

MethodTypeRange
Integer.parseInt()intSmaller range
Long.parseLong()longLarger range

A string like "5000000000" is numeric, but too large for int. In that case, Integer.parseInt() fails while Long.parseLong() succeeds.

Take Quiz

Cheat Sheet

Quick rules

  • Use Integer.parseInt() for integer strings.
  • Use Double.parseDouble() for decimal strings.
  • Use try/catch when you want to match Java's parsing behavior.
  • Use regex when you want custom format rules.
  • Check for null first.
  • Trim input if spaces are possible.

Common helpers

public static boolean isInteger(String value) {
    if (value == null) return false;
    try {
        Integer.parseInt(value);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
public static boolean isDouble(String value) {
    if (value == null) return false;
    try {
        Double.parseDouble(value);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
public static boolean isDigitsOnly(String value) {
    return value != null && value.matches("\\d+");
}

Edge cases

  • null → not numeric
  • "" → not numeric
  • " 42 " → trim first for integer parsing
  • "-7" → valid integer
  • "3.14" → valid double, not valid integer
  • "1e3" → valid double
  • "12a" → not numeric
  • very large numbers may fail for int but work for long or BigDecimal

Rule of thumb

If the question is "Can Java parse this as a number?", try parsing. If the question is "Does this string match my custom numeric format?", validate the format.

FAQ

How do I check if a string is an integer in Java?

Use Integer.parseInt() inside a try/catch block. Return true if parsing succeeds and false if it throws NumberFormatException.

Is regex better than parseInt() for numeric checks?

Not always. Regex is good for custom rules like digits only. If you want to know whether Java accepts the value as a number, parsing is usually the better choice.

Does Integer.parseInt() allow spaces?

No. Strings like " 42 " must usually be trimmed first with trim().

How do I check if a string is a decimal number in Java?

Use Double.parseDouble() in a try/catch block.

What exception is thrown for invalid numbers in Java?

NumberFormatException.

Is "-123" numeric?

Yes, if your definition includes signed integers. Integer.parseInt("-123") succeeds.

Why does "123abc" fail to parse?

Because parsing methods require the entire string to match a valid numeric format. Extra characters make it invalid.

Take Quiz

Mini Project

Description

Build a small Java input validator for a command-line program that reads text values and decides whether each one is a valid integer, a valid decimal number, or not numeric at all. This mirrors real applications that validate user input before saving data or performing calculations.

Goal

Create a Java program that classifies string input as integer, decimal, or invalid and then safely parses valid values.

Requirements

  • Write a method to check whether a string is a valid integer.
  • Write a method to check whether a string is a valid decimal number.
  • Trim user input before validating it.
  • Test the program with examples such as 42, -7, 3.14, abc, and an empty string.
  • Print a clear message showing how each value was classified.
Take Quiz

Keep learning

Related questions

View more