On the difference between equals and = = in java

  • 2021-07-06 11:04:25
  • OfStack

In this article, we share the specific code of the difference between equals and = = in java for your reference. The specific contents are as follows

Example code for java9:


String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
String str4 = new String("abc");

When: str1 = = str2 Output: true When: str1.equals (str2); Output: true
When: str1 = = str3 Output: false When: str1.equals (str3); Output: true
When: str3 = = str4 Output: false When: str3.equals (str4); Output: true

Details involved:
-A string object in the constant pool can be referenced to its equivalent string through the intern method in String

str3.intern () = = str4.intern () Output: true
str1.intern (). equals (str2.intern ()) Output: true
str1.intern () = = str1 Output: false
-String str = new String ("abc"); How many objects have been created?

First of all, we should see if there is a string of "abc" in the constant pool, and if there is (String str = "abc"; If not, create one, and if not, create two (one in the constant pool and one in the heap).

= = Difference from equals:

For = =:

For variables acting on basic data types, directly compare whether their stored "values" are equal;
If the variable acts on the reference type, the address of the pointed object is compared;

For equals:

The equals method cannot be applied to variables of basic data types;
If the equals method in Object is not overridden, the address of the object pointed by the variable of reference type is compared, otherwise, the content is compared;


Related articles: