Register Login

Java Check if String is a Number

Updated Oct 05, 2023

Strings are an essential part of programming that designate texts and help us to get meaningful information across the internet. These provide programmers a way to receive inputs from end-users, manipulating and processing text in various ways, like searching, parsing, replacing, and formatting.

So, programmers often go through phases where they need to check whether their string input contains a valid number (integer or float) or digits. This Java article will cater to distinct methods that allow programmers to check if a string is numeric.

Java has two parts, namely Core Java and Apache Commons, which we will use to check whether our strings contain numeric values or not:

  1. Core Java
  2. Apache Commons
  3. Using Regular Expression

Method 1: Using Core Java to check if the string is numeric

End-users often tend to mistype input values. It is the main reason developers should hold their hands as much as possible during input-output operations. So, Java provides some built-in methods ensuring the exact string format and is the easiest way. These are as follows:

All the above methods will convert a given string into its numeric equivalent. If the conversion is unsuccessful and the string inputs remain a sequence of characters, it returns a NumberFormatException. It indicates that the string is not numeric. Let's try some of these methods and see how these works:

parseInt():

The integer class of Java offers a static method parseInt(). This method will convert a string input into an integer and throw a NumberFormatException if it does not find an integer.

hat is, if it does not include a parsable integer. Next, users can use the try-catch block to catch this exception. It will thus demonstrate that the given string is not a valid integer number.

Syntax:

static int parseInt(String s)
static int parseInt(String s, int radix)

The following are the parameters used:

  • s: This parameter indicates the string representation of decimal.
  • radix: This parameter converts a string into an integer.

Code Snippet:

class demo {
	public static void main(String[] args)
	{
		String a = "'This is Java'";
		String b = "0284";
		try {
			Integer.parseInt(a);
			System.out.println(a + " is numeric");
		}
		catch (NumberFormatException e) {
			System.out.println(a + " is not numeric");
		}
		try {
			Integer.parseInt(b);
			System.out.println(b + " is numeric");
		}
		catch (NumberFormatException e) {
			System.out.println(b + " is not numeric");
		}
	}
}

Output:

Explanation:

Here, we have given two input string values, the first string contains a character value, and the second one contains integers. The parseInt() method checks both the strings and returns "is numeric" if it finds a string. Else, "is not numeric."

But for this, we used the try-catch block that helps the method by enclosing it, which will throw an exception if it does not find string input. The time complexity of the above Java program is O(1). It is due to the execution of a fixed set of operations that do not depend on the input size.

Whereas; the space complexity is also O(1). It is due to using a fixed amount of memory to store the two String variables a and b.

parseFloat():

The integer class of Java offers a static method parseFloat(). This method will convert a string input into an integer and throw a NumberFormatException if it does not find a floating point value.

That is, if it does not include a parsable float. Next, users can use the try-catch block to catch this exception. It will thus demonstrate that the given string is not a valid float number.

Syntax:

public static float parseFloat(String s)

The following are the parameters used:

It has only one parameter s that defines the parsable string.

Code Snippet:

class demo {
	public static void main(String[] args)
	{
		String a = "36hr5.9u";
		String b = "7990.987";
		try {
			Float.parseFloat(a);
			System.out.println(a + " is a a floating point value");
		}
		catch (NumberFormatException e) {
			System.out.println(a + " is not a floating point value");
		}
		try {
			Float.parseFloat(b);
			System.out.println(b + " is a floating point value");
		}
		catch (NumberFormatException e) {
			System.out.println(b + " is not a floating point value");
		}
	}
}

Output:

Explanation:

Inside the class "demo," we created a Java program that checks whether a string contains a floating point value. Then we gave two input string values, the first string contains a character value, and the second one has float, i.e., 7990.987.

The parseInt() method checks both the strings and returns "is a floating point value" if it finds a string. Else, "is a not floating point value." But for this, we used the try-catch block that helps the method by enclosing it, which will throw an exception if it does not find string input. The time complexity of the above Java program is O(1).

It is due to the execution of a fixed set of operations that do not depend on the input size. Whereas; the space complexity is also O(1). It is due to using a fixed amount of memory to store the two String variables a and b.

How to deal with big numbers and check whether the string is numeric?

For this purpose, users can use the BigInteger and BigDecimal class constructors for large numbers. In the following example, we use them and see how they work:

BigInteger() and BigDecimal() are two methods where the BigDecimal class contains a 32-bit integer scale and a random precision integer scale. And the BigInteger() method involves calculating big integer values, which are beyond the limit of other available primitive data types.

Code Snippet:

import Java.math.BigDecimal;
import Java.math.BigInteger;
class demo {
	public static void main(String[] args)
	{
		String a
			= "376787465762898539037699";
		String b = "245tbc6976hy569568uy574635.53y842";
		String c = "2526738";
		try {
			new BigInteger(a);
			System.out.println(a + " is a valid integer value");
		}
		catch (NumberFormatException e) {
			System.out.println(a + " is not a valid integer value");
		}
		try {
			new BigDecimal(b);
			System.out.println(b + " is a valid floating point value");
		}
		catch (NumberFormatException e) {
			System.out.println(b + " is not a valid floating point value");
		}
		try {
			new BigDecimal(c);
			System.out.println(c + " is a valid floating point value");
		}
		catch (NumberFormatException e) {
			System.out.println(c + " is not a valid floating point value");
		}
	}
}

Output:

Explanation:

The BigInteger() method from BigInteger class will check the string contains an integer value, and the BigDecimal() method from the BigDecimal class handles large floating point numbers with great accuracy.

Method 2: Using Apache Commons to check if the string is numeric

Apache Commons is a third-party library that expands the basic Java Framework. It provides two classes that get the string input and check their value.

Users should use an offline Java compiler like NetBeans or Eclipse to execute the following Java program. These are as follows:

NumberUtils.isParsable()

Code Snippet:

Code Snippet:
class demo {
  public static void main(String[] args) {
		String a = "6432";
		if (NumberUtils.isParsable(a)) {
			System.out.println("It is numeric!");
		} else {
			System.out.println("It is not numeric.");
		}
	}
}

Output:

Explanation:

In this example, we used the isParsable() method that accepts string input. It is valid for checking if the string is a parsable number. In place of catching exceptions we use this method which returns an efficient output to avoid frequent exception handling.

NumberUtils.isDigits()

class demo {
	public static boolean only digits(String str, int n)
	{
		for (int i = 0; i < n; i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}
	public static void main(String args[])
	{
		String a = "76543234";
		int l = a.length();
		System.out.println(onlyDigits(a, l));
	}
}

Output:

Explanation:

We used the isDigit() method of the Java class NumberUtils to iterate over each character and check whether our string is a digit. It returns true when it finds the string is numeric, else false.

StringUtils.isNumeric()

import org.apache.commons.lang3.StringUtils;
public class Main {
    public static void main(String[] args) {
        String a = "6824";
        if (StringUtils.isNumeric(a)) {
            System.out.println("String contains digits!");
}       else {
            System.out.println("String does not contain digits!");
        }
    }
}

Output:

Explanation:

Here, we used the StringUtils.isNumeric() to parse the string into an integer. This method is equivalent to the above NumberUtils.isDigits() method, executing if block only if the Java string is numeric.

StringUtils.isNumericSpace()

Users can use this alternative approach if the string contains space with numbers.

Code Snippet:

import org.apache.commons.lang3.StringUtils;
public class Main {
    public static void main(String[] args) {
        String a = "643 72 9242";
        if (StringUtils.isNumericSpace(a)) {
            System.out.println("String contains digits!");
}       else {
            System.out.println("String does not contain digits!");
        }
    }
}

Output:

Explanation:

If the string contains only Unicode digits or spaces, it will execute the if block. And in our program, the method returned the if block, i.e., "String contains digits!" since the string is numeric.

Another method to check if a string is numeric is:

Other than the above methods, users can also use the Regular Expression for the same purpose.

Using Regular Expression:

Syntax:

regex = "[0-9]+";

Code Snippet:

import Java.util.regex.*;
class demo {
	public static boolean
	 onlyDigits(String a)
	{
		String reg = "[0-9]+";
		Pattern b = Pattern.compile(reg);
		if (a == null) {
			return false;
		}
		Matcher m = b.matcher(a);
		return m.matches();
	}
	public static void main(String args[])
	{
		String a = "7259";
		System.out.println(onlyDigits(a));
	}
}

Output:

Explanation:

We matched the given string with the regular expression using the "Pattern.matcher()" method from the Java Matcher class. In the above code example, it will return true if the string matches, else false.

Conclusion

Here, we end this article by explaining all the Java methods that allow us to check whether a string is a number. We hope you all have learned and partake in an out-and-out knowledge of their workings and associated Java classes.

The most common ways are using Core Java and Apache Commons, but we also highlighted regular expressions to match the string and get the desired output.


×