How to check if a String is a number in Java


JavaViews 4253

In this tutorial, we will see different methods on how to check if a string is a number or numeric in Java. A String can contain either a group of characters or digits. When a String contains a group of digits, we can say it contains a number or it is numeric. We always declare a string within double-quotes. Example: String val = "10". In this case, the string is numeric.

Different methods to check if a string is a number

How to check if a string is a number

Check if a string is numeric using Java methods

Java has several built-in methods as below to check if a string is a number or not. If it is not numeric, it will throw NumberFormatException.

  • Integer.parseInt() – converts to an integer number
  • Integer.valueOf() – returns a new Integer() value.
  • Double.parseDouble() – converts to a double value
  • Float.parseFloat() – converts to a float value
  • Long.parseLong() – converts to a long value

Now, let see an example using Integer.parseInt().We can create a user-defined function to check if a string is numeric or not. In the below example, the isInteger() method validates if a string is numeric. We use the Integer.parseInt() method within the try-catch block and try to parse the input string. If it successfully parses, we return true, else return false within the catch block. This is because the parseInt() method throws NumberFormatException if it cannot parse the string. We can then directly call this function from the main method to check if a string is numeric.

public class StringNumericDemo {

  public static void main(String[] args) {
    String s = "100";
    if(isInteger(s)) {
      System.out.println("String is numeric");
    }
    else { bl
      System.out.println("String is not numeric");
    }

  }
  
  public static boolean isInteger(String s) {
    System.out.println(String.format("Parsing string value: \"%s\"", s));
    
    if(s == null || s.equals("")) {
      System.out.println("Cannot parse the string since it either null or empty");
      return false;
    }
    
    try {
      int iVal = Integer.parseInt(s);
      return true;
    }
    catch(NumberFormatException e) {
      System.out.println("Cannot parse the string to integer");
    }
    return false;
  }

}
Parsing string value: "100"
String is numeric

Similarly, we can apply the same logic for parseDouble(), parseLong()or parseFloat() methods as well if we pass the string with double, long, or float value.

Using apache common libraries

Apache common libraries are the most common third-party library that we can use to expand the basic Java framework. It contains the below 2 main libraries to check if a string is numeric or not.

  • NumberUtils
  • StringUtils

To use the above classes, we need to add the corresponding jar files(apache commons lang jar) to the classpath and then import the below statements

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

check if string is numeric

We will now see each of the libraries in detail and implement the same to check if a string is numeric.

NumberUtils.isNumber()

The isNumber() method of the NumberUtils class takes the input string as a parameter and checks if it is a number. If it contains a number, it returns true else returns false.

import org.apache.commons.lang3.math.NumberUtils;

public class StringNumericDemo2 {

  public static void main(String[] args) {
    String s = "123";
    
    if(NumberUtils.isNumber(s)) {
      System.out.println("String is numeric");
    }
    else {
      System.out.println("String is not numeric");
    }

  }

}
String is numeric

Now let’s see what the method returns if we pass alphabets in a string. In this case, it returns false, since it does not contain any numbers.

import org.apache.commons.lang3.math.NumberUtils;

public class StringNumericDemo2 {

  public static void main(String[] args) {
    String s = "abc";
    
    if(NumberUtils.isNumber(s)) {
      System.out.println("String is numeric");
    }
    else {
      System.out.println("String is not numeric");
    }

  }

}
String is not numeric

NumberUtils.isDigits

isDigits() is another method of the NumberUtils class that can check if a string contains number or not.

import org.apache.commons.lang3.math.NumberUtils;

public class StringNumericDemo2 {

  public static void main(String[] args) {
    String s = "123";
    
    if(NumberUtils.isDigits(s)) {
      System.out.println("String is numeric");
    }
    else {
      System.out.println("String is not numeric");
    }

  }

}
String is numeric

StringUtils.isNumeric

The StringUtils class contains isNumeric method that checks if a string contains a number or not. This method is equivalent to the NumberUtils.isNumber() method and works in the same way.  Below is an example of using the StringUtils.isNumeric method.

import org.apache.commons.lang3.StringUtils;

public class StringNumericDemo2 {

  public static void main(String[] args) {
    String s = "123";
    
    if(StringUtils.isNumeric(s))
      System.out.println("String is numeric");
    else
      System.out.println("String is not numeric");

  }

}
String is numeric

StringUtils.isNumericSpace

We can also check if a string contains numbers even if there are spaces in between. For this, we can use the isNumericSpace method of the StringUtils class. Below is an example where the string is numeric and contains spaces.

import org.apache.commons.lang3.StringUtils;

public class StringNumericDemo2 {

  public static void main(String[] args) {
    String s = "123 333 5555";
    
    if(StringUtils.isNumericSpace(s))
      System.out.println("String is numeric");
    else
      System.out.println("String is not numeric");

  }

}
String is numeric

Using RegEx (Regular expression)

Another method to check if a string is numeric is to use the regular expression. A regular expression is a group of patterns that we can match and confirm if it is present in the string. Below is an example of a regex pattern that checks if a string is numeric.

public class StringNumericRegEx {

  public static void main(String[] args) {
    String s = "12345";
    boolean isNum = false;
    
    isNum = s.matches("[0-9]+[\\.]?[0-9]*");
    if(isNum)
      System.out.println("String is numeric");
    else
      System.out.println("String is not numeric");

  }

}
String is numeric

Using Character.isDigit

The Character class contains a method named isDigit() that checks if a particular character is a digit or not. We can create a user-defined function isNumber() to implement this to check if a string is numeric. First, we convert the string to an array of characters and then check if each character is a digit or not using the isDigit() method. If the string contains any single non-numeric value, it returns false, else returns true. Suppose, the input string is “143asd2”, it returns false since it is alphanumeric.

public class StringNumericDemo3 {

  public static void main(String[] args) {
    String s = "14324";
    int l = s.length();
    
    boolean bResult = isNumber(s,l);
    if(bResult) {
      System.out.println(s + " is numeric");
    }
    else
      System.out.println(s + " is not numeric");
  }
  
  static boolean isNumber(String s, int l) {

    if(s == null || l == 0)
      return false;
    
    for(char c: s.toCharArray()) {
      if(!Character.isDigit(c))
        return false;
    }
    return true;
  }

}
14324 is numeric

You might be also interested in Convert String to Int

Reference

Translate »