isEmpty()
分配了內存空間,值為空,是絕對的空,是一種有值(值 = 空)
""
分配了內存空間,值為空字符串,是相對的空,是一種有值(值 = 空字串)
null
是未分配內存空間,無值,是一種無值(值不存在)
得出的結論:
isEmpty()
1.如果不分配內存空間,不能用isEmpty(),否則報空指針異常
2.isEmpty()不能分辨出值是空還是空字符串
null
1.null只能分辨出值是否不分配內存空間
“”
1.不管值是否分配內存空間都不會報錯
例:
public class Test { public static void main(String[] args) { //分配內存空間,值為空 String a = new String(); //分配內存空間,值為空字符串 String b = ""; //未分配內存空間 String c = null; if (a != null) { System.out.println("a值存在"); } if (b != null) { System.out.println("b值存在"); } if (c == null) { System.out.println("c值不存在"); } if (a == "") { System.out.println("a值存在,為空字符串"); } if (b == "") { System.out.println("b值存在,為空字符串"); } //dead code if (c == "") { System.out.println("c值存在,為空字符串"); } if (a.isEmpty()) { System.out.println("a值存在,為空字符串或者為空"); } if (b.isEmpty()) { System.out.println("b值存在,為空字符串或者為空"); } // Null pointer access: The variable c can only be null at this location // if (c.isEmpty()) { // System.out.println("String c=null"); // } } }
結果:
1 a值存在 2 b值存在 3 c值不存在 4 b值存在,為空字符串 5 a值存在,為空字符串或者為空 6 b值存在,為空字符串或者為空