My Java application 'A' is getting mobile number as String from another java application. So after app A gets the mobile number string, I need to validate if that mobile number String has only numbers in it. For validating that I have used a simple logic as below,
public static boolean containsOnlyDigits(String str, int n) {
for (int i = 1; i < n; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
I am checking from i=1 as 1st character will be '+' for country code. This approach is O(n). There is another approach where we can use Double.parseDouble(str). This will throw NumberFormatException so that we can catch and consider it is an Alphanumeric String.
Which of these approaches are best based on performance?
Double.parseDoubleis obviously also running in O(n) (how could it not?!), and so is every other conceivable method.+´sign as you have noted. But also whitespace, parentheses, slashes, dashes and a few other things. Are you sure you need the string to be purely numeric?