String#toCharArray
allocates a new array. Calling charAt
is more efficient, because it avoids creating a new array with a copy of the character data.
That is, prefer this:
boolean isDigits(String string) { for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (!Character.isDigit(c)) { return false; } } return true; }
to this:
boolean isDigits(String string) { // this allocates a new char[] for (char c : string.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; }
Note that many loops over characters can be expressed using streams with String#chars
or String#codePoints
, for example:
boolean isDigits(String string) { string.codePoints().allMatch(Character::isDigit); }