java9 example code:(Recommended learning:java course)
String str1 = "abc"; String str2 = "abc"; String str3 = new String("abc"); String str4 = new String("abc");
当: str1 == str2 输出:true 当:str1.equals(str2); 输出:true 当: str1 == str3 输出:false 当:str1.equals(str3); 输出:true 当: str3 == str4 输出:false 当:str3.equals(str4); 输出:true
Details involved:
- You can use the intern method in String. The string object has a reference to the string that is equal to it in the constant pool.
str3.intern() == str4.intern() 输出:true str1.intern().equals(str2.intern()) 输出:true str1.intern() == str1 输出:false - String str = new String("abc");创建了几个对象?
First of all, check whether there is "abc" in the constant pool. This string, if it exists (String str = "abc"; when it appears), creates one, if not, creates two (one in the constant pool, one in the heap).
The difference between equals and ==
For ==:
Acts on variables of basic data types , then directly compare whether the stored "values" are equal;
acts on reference type variables, then the comparison is the address of the object pointed to;
For equals:
The equals method cannot be applied to variables of basic data types;
If there is no equals method in Object If rewritten, the comparison is the address of the object pointed to by the reference type variable, otherwise the content is compared
The above is the detailed content of The difference between java equals and ==. For more information, please follow other related articles on the PHP Chinese website!