Home >Java >javaTutorial >How to Robustly Check for Null or Empty Strings in Java?
Determing whether a string is not null and not empty is a common requirement in programming. Let's explore a Java example and its corresponding solution.
Consider the code snippet below:
public void doStuff(String str) { if (str != null && str != "") { // handle empty string } }
Here, we want to check if the str string is empty. However, the approach using a simple equals comparison is prone to potential null pointer exceptions.
To improve this code, we can utilize the isEmpty() method, which is available since Java SE 1.6. This method returns true if the string is null or has a length of 0, providing a null-safe and reliable way to check for emptiness.
if (str != null && !str.isEmpty()) { // handle empty string }
Note the order of the conditions using the && operator. By placing the null check first, we avoid the potential runtime error if str is null.
If we want to ignore whitespace characters, we can use a combination of trim() and isEmpty():
if (str != null && !str.trim().isEmpty()) { // handle empty string }
Alternatively, in Java 11 and later, we can use the isBlank() method, which simplifies the whitespace handling:
if (str != null && !str.isBlank()) { // handle empty string }
To make the code more concise and reusable, we can create a utility function:
public static boolean empty(String s) { return s == null || s.trim().isEmpty(); }
This function returns true if the string is null or empty after trimming, otherwise it returns false. Now, we can simply use:
if (!empty(str)) { // handle empty string }
By utilizing these methods, we can ensure that our code robustly handles null strings and correctly checks for emptiness, preventing potential exceptions and ensuring reliable string processing.
The above is the detailed content of How to Robustly Check for Null or Empty Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!