Java(자바)

[Java] StringUtils.isEmpty 와 StringUtils.isBlank 차이

흰오목눈이 2022. 9. 27. 23:32

먼저 공백이 있는 경우란?


따옴표("")사이에 비어 있는 부분을 말한다. (=" ")

""만 리턴한다면 값이 없다고 할 수 있지만 ""사이에 공백이 있으면 공백을 리턴하는 것이 되기 때문에 서버에서 값을 잘못 보내는 경우를 대비하여 확인할 필요가 있다.

 

따옴표 사이의 빨간 네모 부분

 

StringUtils.isEmpty


: 공백이 있는 경우는 처리하지 않는다. 문자열이 null(널)이거나 비어있는 경우("")만 확인한다.

 

 StringUtils.isEmpty(null)      = true (널이라서 참)
 StringUtils.isEmpty("")        = true (비어있어서 참)
 StringUtils.isEmpty(" ")       = false (공백이 있는 경우는 거짓)
 StringUtils.isEmpty("test")     = false (문자가 있으니까 거짓)
 StringUtils.isEmpty("  test  ") = false (공백이 있어도 문자를 포함하니 거짓)

 

StringUtils.isBlank


: 공백이 있는 경우(" ")도 처리한다. 문자열이 null(널)이거나 비어있는 경우("")도 함께 확인한다.

 StringUtils.isBlank(null)      = true (널이니까 참)
 StringUtils.isBlank("")        = true (비어있으니까 참)
 StringUtils.isBlank(" ")       = true (공백이니까 참)
 StringUtils.isBlank("test")     = false (문자열이라서 거짓)
 StringUtils.isBlank("  test  ") = false (공백이 있어도 문자를 포함하니 거짓)

 

응용하기


if (!StringUtils.isEmpty() || !StringUtils.isBlank()) { // null, 비어있는 경우, 공백 모두 체크해서 아닌 경우
   // 값이 있는 경우 아래 코드를 실행함
    ...
}

 

 

참고


https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29

 

StringUtils (Commons Lang 2.6 API)

Splits a String by Character type as returned by java.lang.Character.getType(char). Groups of contiguous characters of the same type are returned as complete tokens, with the following exception: the character of type Character.UPPERCASE_LETTER, if any, im

commons.apache.org

https://stackoverflow.com/questions/23419087/stringutils-isblank-vs-string-isempty

 

StringUtils.isBlank() vs String.isEmpty()

I ran into some code that has the following: String foo = getvalue("foo"); if (StringUtils.isBlank(foo)) doStuff(); else doOtherStuff(); This appears to be functionally equivalent to the

stackoverflow.com