고똘이의 IT 개발이야기

자바에서 문자열 사용을 하다보면 공백체크를 해야할때가 자주 있습니다. 자바스크립트의 경우 따로 유틸이나 메소드를 사용하여 비교할 필요가 없지만 자바의 경우는 유틸이나 메소드를 사용하여 비교를 해줘야합니다.

아래의 소스에서 두가지 공백체크 방법에 대해서 설명드리겠습니다.

 

 

설명

※ 문자열이 공백일경우 isEmpty()는 true를 반환합니다. equals()는 문자열을이 같은지 비교를 하여 같을경우 true를 반환 합니다. 현재 소스상에서 보면 testValue는 문자열이 공백이기 때문에 두 method는 true를 반환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
    String testValue = "";
    
    System.out.println("testValue는 공뱅인가요 : "+ StringUtils.isEmpty(testValue));
    System.out.println("testValue는 공뱅인가요 : "+ "".equals(testValue));
    
    if(StringUtils.isEmpty(testValue)) {
        System.out.println("testValue는 공백입니다.");
    } else {
        System.out.println("testValue는 공백이 아닙니다.");
    }
    
    if("".equals(testValue)) {
        System.out.println("testValue는 공백입니다.");
    } else {
        System.out.println("testValue는 공백이 아닙니다.");
    }
}
 
 

실행결과 참조

 

밑의 소스는 문자열이 존재하기 때문에 false를 반환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) {
    String testValue = "테스트 데이터 입니다.";
    
    System.out.println("testValue는 공뱅인가요 : "+ StringUtils.isEmpty(testValue));
    System.out.println("testValue는 공뱅인가요 : "+ "".equals(testValue));
    
    if(StringUtils.isEmpty(testValue)) {
        System.out.println("testValue는 공백입니다.");
    } else {
        System.out.println("testValue는 공백이 아닙니다.");
    }
    
    if("".equals(testValue)) {
        System.out.println("testValue는 공백입니다.");
    } else {
        System.out.println("testValue는 공백이 아닙니다.");
    }
}
 

 실행결과 참조

 

 

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band