"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Effective checking method for Java strings that are non-empty and non-null

Effective checking method for Java strings that are non-empty and non-null

Posted on 2025-04-16
Browse:659

How Can I Effectively Check if a Java String is Neither Null Nor Empty?

Checking if a String is Not Null and Not Empty

To determine if a string is not null and not empty, Java provides various methods.

Option 1: isEmpty()

For Java versions 1.6 and later, the isEmpty() method provides a concise way to check for emptiness:

if (str != null && !str.isEmpty())

Option 2: str.length() == 0

For Java versions prior to 1.6, str.length() == 0 can be used:

if (str != null && str.length() == 0)

Option 3: trim().isEmpty()

To ignore leading and trailing whitespace, use trim().isEmpty():

if (str != null && !str.trim().isEmpty())

Option 4: isBlank()

Java 11 introduced the isBlank() method, which combines the functionality of isEmpty() and trim():

if (str != null && !str.isBlank())

Handy Function

To simplify the task, consider wrapping the logic in a function:

public static boolean empty(String s) {
  return s == null || s.trim().isEmpty();
}

// Usage
if (!empty(str))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3