Difference between isEmpty and null and ""; Difference between isemptynull
Some time ago I read other people's code and found that sometimes I use isEmpty, sometimes I use null, and sometimes I use "". I am confused about the differences between the three, so I wrote a program to verify it.
1 public class Test {2 public static void main (String [] args) {3 // allocate memory space; Value: 4 String a = new String (); 5 // allocate memory space, value: null String 6 String B = ""; 7 // unallocated memory space 8 String c = null; 9 10 if (! = Null) {11 System. out. println ("a value exists"); 12} 13 if (B! = Null) {14 System. out. println ("B value exists"); 15} 16 if (c = null) {17 System. out. println ("c value does not exist"); 18} 19 if (a = "") {20 System. out. println ("a value exists, it is a Null String"); 21} 22 if (B = "") {23 System. out. println ("B value exists, empty string"); 24} 25 // dead code26 if (c = "") {27 System. out. println ("c value exists, empty string"); 28} 29 if (. isEmpty () {30 System. out. println ("a value exists, it is an empty string or"); 31} 32 if (B. isEmpty () {33 System. out. println ("B value exists, empty string or empty"); 34} 35 // Null pointer access: the variable c can only be null at this location36 // if (c. isEmpty () {37 // System. out. println ("String c = null"); 38 //} 39} 40 41}View Code
The running result is as follows:
1 a value 2 B value 3 c value does not exist 4 B value exist, empty string 5 a value exist, empty string or empty 6 B value exist, empty string orView Code
Conclusion:
IsEmpty ()
1. If no memory space is allocated, isEmpty () cannot be used; otherwise, a null pointer exception is reported.
2. isEmpty () cannot tell whether the value is null or a null string.
Null
1. null can only identify whether the value is not allocated memory space
""
1. No error will be reported regardless of whether the value is allocated memory space