Monday, 10 October 2016

How to check if a String is numeric in Java? Use isNumeric() or isNumber()

In day-to-day programming, you often need to check if a given String  is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use a Regular expression to check if given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third party library like Apache commons lang will handle e.g. hexadecimal and octal String. Hence, In Java application, the simplest way to determine if a String is a number or not is by using Apache Commons lang's isNumber() method, which checks whether the String a valid number in Java or not. Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). Non-hexadecimal strings beginning with a leading zero are treated as octal values. Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal.null and empty/blank String will return false.
Read more »

No comments:

Post a Comment