การตรวจสอบสตริงว่าง (Empty) หรือ Null ใน Java
ใน Java สตริงเป็นออบเจกต์ (Reference type) จึงสามารถเป็น null ได้ สตริงว่าง ("") และ null แตกต่างกัน จึงต้องตรวจสอบทั้งสองกรณี
วิธีการตรวจสอบ
1. ตรวจสอบ Null ก่อน (สำคัญ!)
String str = null;
if (str == null) {
System.out.println("Null string");
} else if (str.isEmpty()) {
System.out.println("Empty string");
} else {
System.out.println("Normal string: " + str);
}
2. ใช้ Objects.equals() (Null-safe)
import java.util.Objects;
if (Objects.equals(str, "")) {
// true ถ้า str เป็น null หรือ ""
}
3. ใช้ Apache Commons Lang (StringUtils)
org.apache.commons.lang3.StringUtils.isEmpty(str); // null หรือ ""
org.apache.commons.lang3.StringUtils.isBlank(str); // null, "", หรือ whitespace เท่านั้น
4. Java 11+: isBlank()
String str = " ";
str.isEmpty(); // false (มี whitespace)
str.isBlank(); // true (whitespace เท่านั้น)
ตัวอย่างโค้ดสมบูรณ์
public class Demo {
public static void main(String[] args) {
String inputString = null;
System.out.println("สตริง: " + inputString);
if (inputString == null) {
System.out.println("สตริงเป็น Null");
} else if (inputString.isEmpty()) {
System.out.println("สตริงเป็น Empty (\"\")");
} else {
System.out.println("สตริงปกติ: " + inputString);
}
}
}
ผลลัพธ์
สตริง: null
สตริงเป็น Null
ตัวอย่างที่ 2: แบบ OOP (Encapsulation)
public class Demo {
static void checkNullOrEmpty(String input) {
if (input == null) {
System.out.println("Null string");
} else if (input.isEmpty()) {
System.out.println("Empty string");
} else if (input.isBlank()) { // Java 11+
System.out.println("Blank string (whitespace only)");
} else {
System.out.println("Normal string: " + input);
}
}
public static void main(String[] args) {
checkNullOrEmpty(null);
checkNullOrEmpty("");
checkNullOrEmpty(" ");
checkNullOrEmpty("Hello");
}
}
ผลลัพธ์
Null string
Empty string
Blank string (whitespace only)
Normal string: Hello
ตารางเปรียบเทียบ
| ค่า | == null | .isEmpty() | .isBlank() (Java 11) | StringUtils.isEmpty | StringUtils.isBlank |
|---|---|---|---|---|---|
| null | true | NPE! | NPE! | true | true |
| "" | false | true | true | true | true |
| " " | false | false | true | false | true |
| "a" | false | false | false | false | false |
แนวทางปฏิบัติที่ดี (Best Practices)
- ตรวจสอบ
null**ก่อน** เรียก.isEmpty()หรือ.isBlank()เพื่อป้องกัน NPE - ใช้
Objects.requireNonNull()สำหรับ validation ตอนรับพารามิเตอร์ - ใช้
StringUtils.isBlank()(Apache Commons) สำหรับโปรเจกต์ที่มี library นี้อยู่แล้ว - Java 11+: ใช้
.isBlank()แทน.trim().isEmpty() - หลีกเลี่ยง
str == ""ใช้str.isEmpty()หรือObjects.equals(str, "")