In our daily development, void judgment should be the most commonly used operation. Therefore, commons lang3 package is always necessary in the project. This package provides us with two methods for void determination, namely StringUtils.isEmpty(CharSequence cs) and StringUtils.isBlank(CharSequence cs). Let's see the difference between the two methods.
1, StringUtils.isEmpty
The source code of isEmpty is as follows:
public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; }
This method determines whether the string is null or its length is zero.
Test effect
public class BlankAndEmpty { public static void main(String[] args) { System.out.println(StringUtils.isEmpty(null)); // true System.out.println(StringUtils.isEmpty("")); //true System.out.println(StringUtils.isEmpty(" ")); //false System.out.println(StringUtils.isEmpty("\t")); //false System.out.println(StringUtils.isEmpty("Java journey")); //false } }
2, StringUtils.isBlank
The source code of isBlank is as follows:
public static boolean isBlank(CharSequence cs) { int strLen = length(cs); if (strLen == 0) { return true; } else { for(int i = 0; i < strLen; ++i) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } }
The method of length(cs) is as follows
public static int length(CharSequence cs) { return cs == null ? 0 : cs.length(); }
This method not only determines whether the string is null and the length is zero, but also determines whether it is a space. If it is a space, it also returns true.
Test effect
public class BlankAndEmpty { public static void main(String[] args) { System.out.println(StringUtils.isBlank(null)); //true System.out.println(StringUtils.isBlank("")); //true System.out.println(StringUtils.isBlank(" ")); //true System.out.println(StringUtils.isBlank("\t")); //true System.out.println(StringUtils.isBlank("Java journey")); //false } }
3, Summary
- isEmpty: returns true if null or ''.
- isBlank: returns true if it is null or '' or a space or tab. isBlank is more accurate.
4, Extension
-
In the actual development, in addition to several cases of isBlank null, we will treat the "null" string as an empty string.
-
We need to judge that several fields cannot be empty at the same time. If we still use isBlank, it will be a bit cumbersome. We can use the variable parameters of String to provide the following utility classes.
public class StringTool { public static boolean isNullStr(String... args) { boolean falg = false; for (String arg : args) { if (StringUtils.isBlank(arg) || arg.equals("null")) { falg = true; return falg; } } return falg; } }
The advantage of this tool class is obvious. On the one hand, it judges the string "null". On the other hand, it has no limit on the number of parameters. As long as one parameter is empty, it returns true.