본문 바로가기
Java

[Java] 문자열을 검사하는 방법 - String isEmpty(), isBlank(), null 체크

by clolee 2025. 4. 1.

isEmpty(), isBlank(), null 체크 정리

검사 방법 설명 예시 코드 주의 사항
str.isEmpty() 문자열의 길이가 0이면 true "".isEmpty()true
" ".isEmpty()false
str == null이면 NullPointerException 발생
str.isBlank() (Java 11+) 문자열이 공백만 포함되거나 비어 있으면 true "".isBlank()true
" ".isBlank()true
"\n\t".isBlank()true
str == null이면 NullPointerException 발생
str == null 문자열이 null 객체인지 확인 str == nulltrue .isEmpty().isBlank() 호출하면 예외 발생하므로 먼저 체크 필요

🔐 안전하게 조합해서 쓰는 법

1. null + isEmpty() 안전 검사


  
if (str != null && str.isEmpty()) {
// str은 null이 아니고, 내용이 완전히 없음
}

2. null + isBlank() 안전 검사 (Java 11 이상)


  
if (str != null && str.isBlank()) {
// str은 null이 아니고, 공백이거나 비어 있음
}

3. null 포함한 통합 체크 함수 만들기 (추천)


  
public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
public static boolean isNullOrBlank(String str) {
return str == null || str.isBlank(); // Java 11 이상
}

사용 예:


  
if (isNullOrBlank(str)) {
System.out.println("문자열이 null이거나 공백입니다.");
}

🧪 예시 비교


  
String a = null;
String b = "";
String c = " ";
String d = "abc";
System.out.println("a == null: " + (a == null)); // true
System.out.println("b.isEmpty(): " + b.isEmpty()); // true
System.out.println("c.isEmpty(): " + c.isEmpty()); // false
System.out.println("c.isBlank(): " + c.isBlank()); // true
System.out.println("d.isBlank(): " + d.isBlank()); // false

✅ 정리 요약

메서드 true가 되는 조건 null 안전성 특징
isEmpty() 길이가 0일 때 ("") ❌ 예외 발생 공백 " "은 false
isBlank() 공백 포함 모든 빈 문자열 ("", " ", "\n") ❌ 예외 발생 Java 11+
== null null 객체일 때 메서드 호출 전에 항상 체크해야 안전
isNullOrEmpty() null 또는 "" 유틸로 자주 사용
isNullOrBlank() null 또는 공백 Java 11+에서 추천

댓글