()
The method comes from the Apache Commons Lang library, which is a very practical tool method to determine whether a string isnull
, empty string or only whitespace characters.
The following is a detailed introduction to this method:
Introduce the library and dependencies
StringUtils
The class belongs to the Apache Commons Lang library, if you want to use itisBlank()
Method, you need to add the dependencies of the library to the project.
Take Maven as an example,Add the following dependencies:
<dependency> <groupId></groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
Method signature
-
isBlank()
The signature of the method is as follows:
public static boolean isBlank(CharSequence cs)
-
parameter:
cs
It's oneCharSequence
type parameter, which means it can receiveString
、StringBuilder
、StringBuffer
Objects of types. -
Return value: Return one
boolean
value of type, if the string isnull
, empty string or only contains whitespace characters, returntrue
; Otherwise returnfalse
。
Method Function
isBlank()
The method checks whether the passed string meets one of the following conditions:
- 1) The string is
null
。 - 2) The string length is 0 (i.e., empty string).
- 3) The string only contains whitespace characters (such as spaces, tabs, line breaks, etc.).
Sample code
import .; public class StringUtilsIsBlankExample { public static void main(String[] args) { // Test null string String str1 = null; ((str1)); // Test empty string String str2 = ""; ((str2)); // Test strings containing only whitespace characters String str3 = " "; ((str3)); // Test strings containing non-whitespace characters String str4 = "hello"; ((str4)); } }
Code explanation
- When the incoming string is
null
hour,isBlank()
Method returntrue
。 - When the passed string is an empty string,
isBlank()
Method returntrue
。 - When the passed string contains only whitespace characters,
isBlank()
Method returntrue
。 - When the passed string contains non-whitespace characters,
isBlank()
Method returnfalse
。
Comparison with other methods
-
isEmpty()
method:
()
Method only determines whether the string isnull
Or an empty string, which does not check whether the string contains only whitespace characters.
For example,(" ")
Will returnfalse
,and(" ")
Will returntrue
。
-
String
ClassicisEmpty()
method:
String
ClassicisEmpty()
Methods can only be usedString
Object, and only determine whether the string length is 0, cannot be processednull
value.
If truenull
CallisEmpty()
The method will be thrownNullPointerException
abnormal.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.