"" Memory allocated; null
When a null string is called, a null pointer is thrown.
"" Is a string. It exists in the memory. It can use methods in the object (such as "". tostring (); "". Equals ())
Null is an empty object. It does not exist in the memory. It cannot use methods in the object.
"" Memory occupied .. a space will be allocated in the memory.
Null does not occupy memory. It is a null reference.
String str1 = NULL; STR reference is empty
String str2 = ""; STR apply an empty string
That is, no space is allocated for null. "" space is allocated. Therefore, str1 is not an instantiated object, and [size = medium] [/size] str2 has been instantiated.
Note that "" is an object because null is not an object. Therefore, the comparison must be if (str1 = NULL) {...} And if (str2.equals ("")){}
Objects are compared with equals, and null objects are compared with equal signs. Therefore, if str1 = NULL; the following statement is incorrect:
If (str1.equals ("") | str1 = NULL) {// If str1 has no value, then ....
//....
}
The correct syntax is if (str1 = NULL | str1.equals ("") {// first judge whether it is an object. If yes, then judge whether it is a null string.
//...
}
In Java, class objects are accessed using handles, just like pointers in C.
In Java, there are two methods that are equal. One is the equals () method in string, and the other is the equals () method in string. The difference between the two is that the former is the address, the latter compares the content.
For example, you have written such a statement.
String str1, str2;
That is to define two handles pointing to different string instances. Now they all point to null, so str1 = str2 = NULL, you cannot use the length () method at this time, because, none of them point to a specific object. If this method is called, an nullpointerexception is returned. Then, if you write such a statement str1 = new string (); then str1 will point to a specific string instance, so str1! = Str2, str1! = NULL, and more importantly, str1! = "", Because "" And str1 refer to two different addresses. The return value of str1.length () is 0, that is, the string is null.
Even if you write
Str2 = new string (); it is still str1! = Str2, because they point to two different addresses, but if you use str1.equals (str2), the return value is true, because they have the same content and are empty.