Java determines if a string is empty and a string is numeric

  • 2020-04-01 03:21:46
  • OfStack

Null on String:

//That's right
if (selection != null && !selection.equals("")) {
      whereClause += selection;
  }

//This is wrong
if (!selection.equals("") && selection != null) {
      whereClause += selection;
  }

Note: "==" compares the values of the two variables themselves, that is, the first addresses of the two objects in memory. Equals (), on the other hand, compares whether the contents of the string are the same. In the second way, once selection is really null, the null pointer exception will be directly invoked when the equals method is executed, so that execution will not continue.

To determine whether the string is a number:


//Call functions that come with Java
public static boolean isNumeric(String number) {
  for (int i = number.length(); --i >= 0;) {
      if (!Character.isDigit(number.charAt(i))) {
          return false;
      }
  }
  return true;
}
//Using regular expressions
public static boolean isNumeric(String number) {
  Pattern pattern = Pattern.compile("[0-9]*");
  return pattern.matcher(str).matches();
}
//Using the ASCII
public static boolean isNumeric(String number) {
  for (int i = str.length(); --i >= 0;) {
      int chr = str.charAt(i);
      if (chr < 48 || chr > 57)
          return false;
  }
  return true;
}


Related articles: