In Java, strings can be either null or empty. A null string means that the variable has not been initialized with a value, while an empty string is a string that contains no characters. In this tutorial, we will learn how to check if a string is null or empty and perform actions accordingly.
Checking for Null Strings
To check if a string is null, you can use the ==
operator. This operator checks if the object being referred to by the variable is the same as the object on the right-hand side of the operator.
String myString = null;
if (myString == null) {
System.out.println("The string is null");
}
Checking for Empty Strings
To check if a string is empty, you can use the isEmpty()
method. This method returns true if the string contains no characters, and false otherwise.
String myString = "";
if (myString.isEmpty()) {
System.out.println("The string is empty");
}
Checking for Both Null and Empty Strings
In many cases, you want to perform an action only if a string has a meaningful value. To do this, you can combine the null check with the empty check using the &&
operator.
String myString = "";
if (myString != null && !myString.isEmpty()) {
System.out.println("The string is not null and not empty");
}
This code will first check if myString
is not null. If it’s not null, then it will check if myString
is not empty using the isEmpty()
method.
Using Apache Commons
If you are working with a lot of strings in your application, consider using Apache Commons’ StringUtils
class. It provides many useful methods for string manipulation and checking.
import org.apache.commons.lang3.StringUtils;
String myString = "";
if (StringUtils.isNotEmpty(myString)) {
System.out.println("The string is not empty");
}
Best Practices
When comparing strings with literals, it’s a good practice to reverse the comparison order. This way, you don’t need to perform a null check.
String myString = "hello";
if ("hello".equals(myString)) {
System.out.println("The string is hello");
}
In summary, checking for null and empty strings in Java involves using the ==
operator for null checks, the isEmpty()
method for empty checks, and combining these with the &&
operator to ensure that a string has a meaningful value.
Kotlin Equivalent
For those working with Kotlin, you can use the following methods to check if a string is null or empty:
val myString: String? = ""
if (myString.isNullOrEmpty()) {
println("The string is null or empty")
}
if (myString.isEmpty()) {
println("The string is empty")
}
Note that in Kotlin, the isNullOrEmpty()
method checks if a string is either null or empty.