In Java, determine whether the string is empty ornull
It is a very common operation.
Below is a few different ways of judgment.
1. Manual judgment
You can pass== null
Determine whether the string isnull
,uselength() == 0
Determines whether the string is empty.
The sample code is as follows:
public class StringCheckExample { public static void main(String[] args) { String str1 = null; String str2 = ""; String str3 = "hello"; (isNullOrEmpty(str1)); (isNullOrEmpty(str2)); (isNullOrEmpty(str3)); } public static boolean isNullOrEmpty(String str) { return str == null || () == 0; } }
Code explanation
-
str == null
: Used to determine whether the string isnull
。 -
() == 0
: Used to determine whether the string is empty.
2. Use the isEmpty() method
Starting with Java 6,String
Class providedisEmpty()
Method, this method can determine whether the length of the string is 0.
The sample code is as follows:
public class StringCheckExample { public static void main(String[] args) { String str1 = null; String str2 = ""; String str3 = "hello"; (isNullOrEmpty(str1)); (isNullOrEmpty(str2)); (isNullOrEmpty(str3)); } public static boolean isNullOrEmpty(String str) { return str == null || (); } }
Code explanation
-
str == null
: Determine whether the string isnull
。 -
()
: Determine whether the string length is 0.
3. Use the Apache Commons Lang library
The Apache Commons Lang library providesStringUtils
class, ofisBlank()
andisEmpty()
Methods can easily determine whether the string is empty ornull
。
To use this library, you need to add dependencies to your project.
Take Maven as an example,Add the following dependencies to:
<dependency> <groupId></groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
The sample code is as follows:
import .; public class StringCheckExample { public static void main(String[] args) { String str1 = null; String str2 = ""; String str3 = "hello"; ((str1)); ((str2)); ((str3)); } }
Code explanation
-
()
: You can determine whether the string isnull
, empty strings or only whitespace characters. -
()
: Only determine whether the string isnull
Or an empty string.
4. Use Java 11's isBlank() method
Starting with Java 11,String
Class providedisBlank()
Method, this method can determine whether the string isnull
, empty strings or only whitespace characters.
The sample code is as follows:
public class StringCheckExample { public static void main(String[] args) { String str1 = null; String str2 = ""; String str3 = "hello"; (isNullOrBlank(str1)); (isNullOrBlank(str2)); (isNullOrBlank(str3)); } public static boolean isNullOrBlank(String str) { return str == null || (); } }
Code explanation
-
str == null
: Determine whether the string isnull
。 -
()
: Determine whether the string is empty or contains only whitespace characters.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.