1. String’s == and equal()
In the equality judgment of strings, == judges whether the addresses are the same, and equal() judges whether the character values are the same. Most of the time the results of == and equal() are the same. This is because the String object is in immutable mode. If you do not explicitly create a new String object, Java's default for saving the String object is to put the newly generated String object into a buffer, and then determine the buffer each time. Whether this object already exists, if so, then the String object with the same character value created later will also point to the address where the character value object was originally created. That is to say, when the character values are the same, the geology is also the same in most cases. == has the same effect as equal(). However, when the object is generated by str = new String("abc") instead of directly assigned as str = "abc", or after some string connection processing, or generated through objects such as StringBuffer, new ones will be opened in the memory. For addresses, the results of == and equal() are different at this time.
Is it a little complicated? Here you need some understanding of memory, stack, and object storage. I don't want to dwell on this issue. If you don’t understand, just remember that if you want to determine whether the character values of two strings are equal and there are no other requirements, please use equal() instead of ==. As for when you need to use ==, I Think that when you need it, you will understand it naturally. In fact, for string judgment, we rarely need to use ==.
2. About str.equal("abc") and "abc".equal(str)
There seems to be a lot of debate about this. Writing the first constant at the end may be in line with most people's habits and our logical thinking. But one more judgment is needed to determine whether str is null. Otherwise, an exception may occur here. The latter way of writing does not require more judgment on whether it is null. As far as my personal preference is concerned, I prefer the latter way of writing.
3. About null of String
/**
* Test the situation when java's String is null
* create date:2009-6-3
* author:Administrator
*
*/
public static void testNull(){
String a= null,b = null,c="hehe";
System.out.println(a == null);
System.out.println(a+b+c);
}
Method execution result:
true
nullnull haha So everyone should pay attention when doing string merging operations, don't forget to check for null, otherwise the result will not be very satisfying!