= = can be used to compare a base type to a reference type, and for a base type variable to compare whether its stored value is equal, and for a reference type, whether it points to the same object.
Such as:
int a = 10;
int B = 20;
Double d = 10.0;
The result of A==b is false, because the value of a and B are not equal;
The result of A==d is true because the values of a and d are equal.
Keyboard Objone = new Keyboard ();
Keyboard objtwo = new Keyboard ();
Keyboard objthree = Objone;
The result of Objone = = Objtwo is False, because Objone and Objtwo point to different objects;
Objone = = Objthree The result is true, because Objone and Objthree point to the same object.
equals can only be used for comparisons of reference type variables, and if the Equals method is not overridden, the comparison is whether it points to the same object.
Such as:
Keyboard Objone = new Keyboard ();
Keyboard objtwo = new Keyboard ();
Keyboard objthree = Objone;
The result of Objone.equals (Objtwo) is false, because Objone and Objtwo point to different objects;
The result of Objone.equals (Objthree) is true, because Objone and Objthree point to the same object.
- The string class overrides the Equals method to compare whether the strings stored by the pointed string object are equal
Such as:
String str1 = new String ("Hello");
String str2 = new String ("Hello");
String str3 = new String ("good");
The result of Str1.equals (STR2) is true because str1 stores strings equal to the string object that the str2 points to;
The result of Str1.equals (STR3) is false, because the strings stored by STR1 and the string object that the STR3 points to are not equal.
The result of STR1==STR2 in the above example is false, because str1, str2 point to different objects.
Another example:
String STR4 = "Hello";
String STR5 = "Hello";
STR4 = = STR5 result is true, this is because STR4, STR5 point to the same string object.
This means that only a "Hello" object is created, which is different from creating a new object each time it is created.
= = and equals in Java