Java checking if string is number one

4 Ways to Check if String is Integer in Java

There are situations when we need to check if a string is an integer. I will be telling you some of the ways to perform this operation in this article. Let us go through all the methods one after another along with their explanation.

1. Using parseInt method

The parseInt method comes inside the Integer class which checks whether a string can be converted to a number. If it is possible then the method returns the converted integer value otherwise it throws a NumberFormatException error.

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and calling the numcheck() method. Inside the numcheck method try and catch block is used to check whether we are able to convert the input string to an integer or not. If it’s not possible then the catch block returns false followed by printing “No given string is not an integer”. If the given string can be converted successfully into an integer then we simply print “Yes given string is an integer”.

Читайте также:  Css и xpath селекторы

2. Using Regular Expressions (regex)

We can use java.util.regex to find certain patterns in the given string. Therefore it can also be used to check whether the given string consists of only numerical digits or not.

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then using the try & catch block to check whether a given string is an integer or not. Inside the try block, a regex function matches() is used if it executes successfully then the instructions on the next line are printed. Otherwise, catch block is executed and we print that the given string is not a valid integer number.

3. Using BigInteger Method

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then using the try & catch block to check whether a given string is an integer or not. Inside the try block, we will use the BigInteger constructor for bigger numbers. If it is executed successfully then we can simply print the given number as an integer. Otherwise, the code written in the catch block is executed through which we can print that the given number is not an integer.

4. Using for Loop

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then checking each character whether it’s a digit or not. Here an integer variable wrong is created which is incremented if we encounter any character that isn’t a digit. At last, the if & else condition is used to check whether the value of wrong is 0 or more. If it’s 0 then the given string is a valid integer number. Otherwise, the given string isn’t a valid integer number.

Conclusion

Through this blog, we learned different methods to check whether an input string is an integer or not. Majorly build-in methods along with the simple method of using for loop are discussed above. There were some more methods in the Apache Comms library that provides the same functionality. You can explore this third party library if you want to learn more. I hope you were able to grasp the concepts clearly, feel free to comment below if you are facing any doubts. I will be happy to resolve all the queries.

Источник

Java: Check if String is a Number

Strings are a handy way of getting information across and getting input from a user.

In this article, we will go through a couple of ways check if a String is Numeric in Java — that is to say, if a String represents a numeric value.

Check if String is Numeric with Core Java

Users tend to mistype input values fairly often, which is why developers have to hold their hand as much as possible during IO operations.

The easiest way of checking if a String is a numeric or not is by using one of the following built-in Java methods:

  1. Integer.parseInt()
  2. Integer.valueOf()
  3. Double.parseDouble()
  4. Float.parseFloat()
  5. Long.parseLong()

These methods convert a given String into its numeric equivalent. If they can’t convert it, a NumberFormatException is thrown, indicating that the String wasn’t numeric.

It’s worth noting that Integer.valueOf() returns a new Integer() , while Integer.parseInt() returns a primitive int . Keep this in mind if such a difference would change the flow of your program.

String string = "10"; try < intValue = Integer.parseInt(string); return true; > catch (NumberFormatException e) < System.out.println("Input String cannot be parsed to Integer."); > 

Now, we can abstract this functionality into a helper method for convenience:

public static boolean isNumeric(String string) < int intValue; System.out.println(String.format("Parsing string: \"%s\"", string)); if(string == null || string.equals("")) < System.out.println("String cannot be parsed, it is null or empty."); return false; > try < intValue = Integer.parseInt(string); return true; > catch (NumberFormatException e) < System.out.println("Input String cannot be parsed to Integer."); > return false; > 
String string = "10"; if(isNumeric(string)) < System.out.println("String is numeric!"); // Do something > else < System.out.println("String is not numeric."); > 

Running this code would result in:

Parsing string: "10" String is numeric! 

On the other hand, if we expect the String to contain a really big number, then we can call the BigInteger(String) constructor, which translates the String representation into a BigInteger .

Check if String is Numeric with Apache Commons

Apache Commons is one of the most used third-party libraries for expanding the basic Java Framework. It gives us more fine control over core Java classes, in this case, Strings.

We’ll be looking at two classes from the Apache Commons library:

Both of which are very similar to their vanilla Java class counterparts, but with an emphasis on null-safe operations (on numbers and strings respectively), meaning we can even define default values for missing (null) values.

Let’s now take a look at how we can check for numeric values using these methods.

NumberUtils.isParsable()

This method accepts a String and checks if it’s a parsable number or not, we can be use this method instead of catching an exception when calling one of the methods we mentioned earlier.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This is very good because solutions that involve frequent exception handling should be avoided if possible — this is exactly what this method helps us with.

Note that hexadecimal numbers and scientific notations are not considered parsable.

Now, we don’t really even need a convenience helper method, as isParseable() returns a boolean itself:

String string = "10"; if (NumberUtils.isParsable(string)) < System.out.println("String is numeric!"); > else < System.out.println("String is not numeric."); > 

NumberUtils.isCreatable()

This method also accepts a String and checks if it’s a valid Java number. With this method we can cover even more numbers, because a valid Java number includes even hexadecimal and octal numbers, scientific notation, as well as numbers marked with a type qualifier.

Now, we can even use something along the lines of:

String string = "0x10AB"; if (NumberUtils.isCreatable(string)) < System.out.println("String contains a creatable number!"); > else < System.out.println("String doesn't contain creatable number."); > 
String contains a creatable number! 

NumberUtils.isDigits()

The NumberUtils.isDigits() method checks if a string contains only Unicode digits. If the String contains a leading sign or decimal point the method will return false :

String string = "25"; if (NumberUtils.isDigits(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); > 

StringUtils.isNumeric()

The StringUtils.isNumeric() is the StringUtils equivalent of NumberUtils.isDigits() .

If the String passes the numeric test, it may still generate a NumberFormatException error when parsed by the methods we mentioned earlier, for example if it is out of range for int or long .

Using this method we can determine if we can parse String into an Integer :

String string = "25"; if (StringUtils.isNumeric(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); > 

StringUtils.isNumericSpace()

Additionally, if we expect to find more numbers within a String, we can use isNumericSpace , another useful StringUtils method worth mentioning. It checks if the String contains only Unicode digits or spaces.

Let’s check a String that contains numbers and spaces:

String string = "25 50 15"; if (StringUtils.isNumericSpace(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); > 

Check if String is Numeric with Regex

Even though most developers will be content with using an already implemented method, sometimes you might have very specific pattern checking:

public static boolean isNumeric(String string) < // Checks if the provided string // is a numeric by applying a regular // expression on it. String regex = "4+[\\.]?6*"; return Pattern.matches(regex, string); > 

And then, we can call this method:

System.out.println("123: " + isStringNumeric2("123")); System.out.println("I'm totally a numeric, trust me: " + isStringNumeric2("I'm totally a numeric, trust me")); 

Running this gives us the following output:

123: true I'm totally a numeric, trust me: false 

Conclusion

In this article, we’ve covered several ways to check if a String is numeric or not (represents a number) in Java.

We’ve started off using Core Java, and catching a NumberFormatException , after which we’ve used the Apache Commons library. From there, we’ve utilized the StringUtils and NumberUtils classes to check whether a String is numeric or not, with various formats.

Источник

Оцените статью