본문 바로가기
개발&프로그래밍

[JAVA] Java의 String Empty 와 Blank 체크하기

by 재아군 2022. 3. 18.

 

Java의 String Empty 와 Blank 체크하기에 대해 알아봅니다.

 

 

 

Empty와 Blank의 차이

 

Sring Empty : null 이거나 length(길이)가 없는 String

String Blank : 공백으로만 되어있는 String

 

 

Empty String

 

Java6 이상부터는 String 클래스의 isEmpty 메소드로 체크하면 됩니다.

String test = " ";
if (test.isEmpty()) {
    log.info("isEmpty");
} else {
    log.info("isNotEmpty"); 
}

//결과는 isNotEmpty 가 출력됩니다.

 

test라는 String이 null이 들어올 수 있기 때문에 조건을 추가해준다면 다음과 같이 empty 를 체크하면 됩니다.

String test = null;
if (test == null || test.isEmpty()) {
    log.info("isEmpty");
} else {
    log.info("isNotEmpty");
}

//결과는 isEmpty가 출력됩니다.

 

Java5 이하 버전에서는 String 클래스의 isEmpty 메서드를 지원하지 않기 때문에 length 메서드로 체크하면 됩니다.

boolean isEmptyString(String string) {
    return string == null || string.length() == 0;
}

 

Blank String

 

빈 문자열인지 체크하려면 String의 trim 메소드를 이용할 수 있습니다. (String의 trim은 앞 뒤 문자를 제거합니다.)

boolean isBlankString(String string) {
    return string == null || string.trim().isEmpty();
}

 

Java 11부터는 trim 메소드를 사용하지 않고 대신에 isBlank 메서드를 사용할 수 있습니다.

boolean isBlankString(String string) {
    return string == null || string.isBlank();
}

 

 

 

Apache Commons 라이브러리 이용하기

 

Apache Commons 라이브러리에서는 StringUtils가 있습니다. 이 클래스에는 isEmpty 메소드와 isBlank 메소드가 있습니다.

 

String test = " ";
log.info("isBlank : {} ", StringUtils.isBlank(test)); //출력 : isBlank : true
log.info("isEmpty : {} ", StringUtils.isEmpty(test)); //출력 : isEmpty : false

 

Apache Commons 라이브러리 StringUtils.isBlank 내부 구현을 살펴봅니다.

 

/*
Checks if a CharSequence is empty (""), null or whitespace only.
Whitespace is defined by Character.isWhitespace(char).
       StringUtils.isBlank(null)      = true
       StringUtils.isBlank("")        = true
       StringUtils.isBlank(" ")       = true
       StringUtils.isBlank("bob")     = false
       StringUtils.isBlank("  bob  ") = false
       
Params:
cs – the CharSequence to check, may be null
Returns:
true if the CharSequence is null, empty or whitespace only
Since:
2.0
*/ 

public static boolean isBlank(final CharSequence cs) {
    final int strLen = length(cs);
    if (strLen == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}

 

Apache Commons 라이브러리 StringUtils.isEmpty 내부 구현을 살펴봅니다.

/*
Checks if a CharSequence is empty ("") or null.
       StringUtils.isEmpty(null)      = true
       StringUtils.isEmpty("")        = true
       StringUtils.isEmpty(" ")       = false
       StringUtils.isEmpty("bob")     = false
       StringUtils.isEmpty("  bob  ") = false
       
NOTE: This method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is available in isBlank().
Params:
cs – the CharSequence to check, may be null
Returns:
true if the CharSequence is empty or null
Since:
3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/ 

public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

 

Google의 Guava 라이브러리

String이 null인지 비어있는지는 확인하지만, 공백만 있는지는 확인하지 않습니다.

 

Strings.isNullOrEmpty(string)
String test = " ";
log.info("isNullOrEmpty : {} ", Strings.isNullOrEmpty(test)); // 출력 : isNullOrEmpty : false

 

Guava 라이브러리의 Strings.isNullOrEmpty 메소드 살펴보기

public static boolean isNullOrEmpty(@Nullable String string) {
    return Platform.stringIsNullOrEmpty(string);
  }
  
//Platform 클래스
static boolean stringIsNullOrEmpty(@Nullable String string) {
	return string == null || string.isEmpty();
}

댓글