빈 문자열, NULL검사 방법에는 아래가 존재합니다
#length
//길이 검사
String str = "";
if(str.length == 0){
}
//공백 제거 후 길이 검사
String str = "";
if(str.trim().length == 0){ // 공백 스페이스 제거 후 길이 검사
}
//NULL 검사 추가
String str = "";
if(str.length == 0 || str == NULL){
}
#equals()
String str = "";
if(str.equals("")){
}
//NULL 검사 추가
String str = "";
if(str.equals("") || str == NULL){
}
#isEmpty() : JAVA6 이상
String str = "";
if(str.isEmpty()){
}
String str = "";
if(str.trim().isEmpty()){//공백 스페이스 제거 후 NULL검사
}
//NULL 검사 추가
String str = "";
if(str.isEmpty("") || str == NULL){
}
#isBlank() : JAVA11 이상, NULL이거나 공백 스페이스면 TRUE를 반환
String str = "";
if(str.isBlank()){
}
//NULL 검사 추가
String str = "";
if(str.isBlank("") || str == NULL){
}
하지만 위의 방법은 빈값 검사일뿐 NULL처리에 대한 코드가 없어서
값이 NULL일 경우 IF문에 str == NULL과 같은 NULL에 대한 대응을 하지 않으면
결과에서 NullPointException에러를 발생시킵니다
그 외에 외부 라이브러리를 사용한 방법이 있는데
Apache Commons Lang입니다
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
Maven Repository: org.apache.commons » commons-lang3
Apache Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang. VersionRepositoryUsagesDate3.11.x3.11Central1,231Jul, 20203.10.x3.10Central1
mvnrepository.com
#Maven
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
#Gradle
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
위 코드를 추가해서 사용가능합니다
Apache Commons Lang을 사용했을 경우 NULL검사를 할 필요가 없습니다
#StringUtils.isEmpty() : 문자열이 빈값이거나 공백스페이스 NULL이면 TRUE 반환
String str = "";
if(StringUtils.isEmpty(str)){
}
#StringUtils.isBlank() : 문자열이 빈값이거나 NULL이면 TRUE 반환, 공백스페이스는 FALSE
String str = "";
if(StringUtils.isBlank(str)){
}
'Programming > JAVA' 카테고리의 다른 글
| [JAVA] 접근 제한자 (0) | 2020.12.18 |
|---|---|
| [SPRING] ResultMap (0) | 2020.12.11 |
| [JAVA] 문자열 비교 (0) | 2020.11.19 |
| [JAVA] 대소문자 변환 (0) | 2020.11.19 |
| [SPRING] Spring 구조 및 DTO, VO 개념 (0) | 2020.10.07 |



