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

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

Mary-Kate Olsen
Release: 2024-12-14 12:44:11
Original
528 people have browsed it

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())
Copy after login

Option 2: str.length() == 0

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

if (str != null && str.length() == 0)
Copy after login

Option 3: trim().isEmpty()

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

if (str != null && !str.trim().isEmpty())
Copy after login

Option 4: isBlank()

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

if (str != null && !str.isBlank())
Copy after login

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))
Copy after login

The above is the detailed content of How Can I Effectively Check if a Java String is Neither Null Nor Empty?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template