Home  >  Article  >  Java  >  Java determines whether the string is empty and whether the string is a number

Java determines whether the string is empty and whether the string is a number

高洛峰
高洛峰Original
2017-01-16 10:50:381555browse

About the null judgment of String:

//这是对的
if (selection != null && !selection.equals("")) {
      whereClause += selection;
  }

//这是错的
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 the memory. And "equals()" compares whether the content contained in the string is the same. In the second way of writing, once selection is really null, a null pointer exception will be reported directly when executing the equals method and execution will not continue.

Determine whether a string is a number:

// 调用java自带的函数
public static boolean isNumeric(String number) {
  for (int i = number.length(); --i >= 0;) {
      if (!Character.isDigit(number.charAt(i))) {
          return false;
      }
  }
  return true;
}
// 使用正则表达式
public static boolean isNumeric(String number) {
  Pattern pattern = Pattern.compile("[0-9]*");
  return pattern.matcher(str).matches();
}
// 利用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;
}

For more Java-related articles about determining whether a string is empty and whether a string is a number, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn