4. Checking whether a string contains only digits

The solution to this problem relies on the Character.isDigit() or String.matches() method. 

The solution relying on Character.isDigit() is pretty simple and fast—loop the string characters and break the loop if this method returns false:

public static boolean containsOnlyDigits(String str) {

for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}

return true;
}

In Java 8 functional style, the preceding code can be rewritten using anyMatch():

public static boolean containsOnlyDigits(String str) {

return !str.chars()
.anyMatch(n -> !Character.isDigit(n));
}

Another solution relies on String.matches(). This method returns a boolean value indicating whether or not this string matches the given regular expression:

public static boolean containsOnlyDigits(String str) {

return str.matches("[0-9]+");
}

Notice that Java 8 functional style and regular expression-based solutions are usually slow, so if speed is a requirement, then it's better to rely on the first solution using Character.isDigit().

Avoid solving this problem via parseInt() or parseLong(). First of all, it's bad practice to catch NumberFormatException and take business logic decisions in the catch block. Second, these methods verify whether the string is a valid number, not whether it contains only digits (for example, -4 is valid).
For third-party library support, please consider the Apache Commons Lang, StringUtils.isNumeric().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.151.107