"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Java字符串非空且非null的有效检查方法

Java字符串非空且非null的有效检查方法

2025-07-25에 게시되었습니다
검색:753

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))
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3