How to Check if String is Null in Java - Simple Guide
In Java, you check if a string is null by using the condition
string == null. This compares the string variable to null to see if it has no value assigned.Syntax
Use the equality operator == to check if a string is null. The syntax is:
stringVariable == nullreturnstrueif the string has no value.stringVariable != nullreturnstrueif the string has some value.
java
if (stringVariable == null) { // string is null } else { // string is not null }
Example
This example shows how to check if a string is null and print a message accordingly.
java
public class NullCheckExample { public static void main(String[] args) { String text = null; if (text == null) { System.out.println("The string is null."); } else { System.out.println("The string is not null."); } text = "Hello"; if (text == null) { System.out.println("The string is null."); } else { System.out.println("The string is not null."); } } }
Output
The string is null.
The string is not null.
Common Pitfalls
A common mistake is to use string.equals(null) to check for null. This causes a NullPointerException if the string is actually null. Always use == null to check for null before calling any methods on the string.
Wrong way:
if (string.equals(null)) {
// This throws NullPointerException if string is null
}Right way:
if (string == null) {
// Safe null check
}Quick Reference
| Check | Syntax | Meaning |
|---|---|---|
| Is null | string == null | String has no value assigned |
| Is not null | string != null | String has some value |
Key Takeaways
Use 'string == null' to safely check if a string is null in Java.
Never use 'string.equals(null)' as it throws an error if string is null.
Check for null before calling any methods on a string to avoid exceptions.
Use 'string != null' to confirm a string has a value before using it.