1. Basic data types
BYTE, short, int, long, double, Float,boolean,char
The comparison between them, applying the double equals sign (= =), compares their values.
2. Composite data type (Class)
When they compare with (= =), they compare the storage address in memory, so unless it is the same new object, their comparison result is true, otherwise the result is false. All classes in Java are inherited from the base class of object, in the base class in object defines a method of equals, the Equals source of object:
1 Public Boolean equals (Object obj) {2 return ( this = = obj); 3 }
The initial behavior of this method is to compare the memory address of the object, but in some class libraries This method is overridden, such as string,integer,date in these classes where equals has its own implementation, and is no longer a comparison class in the heap memory of the storage address.
For the equals comparison between composite data types, the comparison between them is based on the address value of the location in memory where the Equals method is not covered, because the Equals method of object is compared with the double equals sign (= =). So the result of the comparison is the same as the double equals sign (= =).
Sample code:
1 Public classTest {2 Public Static voidtest01 () {3String S1 = "Hello";4String s2 = "Hello";5System.out.print ("test01:");6 if(S1 = =S2) {7System.out.print ("s1==s2" + "" ");8}Else {9System.out.print ("s1!=s2" + "" ");Ten } One if(s1.equals (S2)) { ASystem.out.print ("S1 equals S2"); -}Else { -System.out.print ("S1 not equals S2"); the } - } - - Public Static voidtest02 () { +String S1 = "Hello"; -String s2 =NewString ("Hello"); +System.out.print ("\ntest02:"); A if(S1 = =S2) { atSystem.out.print ("s1==s2" + "" "); -}Else { -System.out.print ("s1!=s2" + "" "); - } - if(s1.equals (S2)) { -System.out.print ("S1 equals S2"); in}Else { -System.out.print ("S1 not equals S2"); to } + } - the Public Static voidtest03 () { *String S1 = "Hello"; $String s2 =NewString ("Hello");Panax NotoginsengSystem.out.print ("\ntest03:"); -S2 =S2.intern (); the if(S1 = =S2) { +System.out.print ("s1==s2" + "" "); A}Else { theSystem.out.print ("s1!=s2" + "" "); + } - if(s1.equals (S2)) { $System.out.print ("S1 equals S2"); $}Else { -System.out.print ("S1 not equals S2"); - } the } - Wuyi Public Static voidMain (string[] args) { the test01 (); - test02 (); Wu test03 (); - inti = 0; AboutInteger j =NewInteger (0); $System.out.println ("\ n" + (i = =j)); - System.out.println (J.equals (i)); - } -}
Output Result:
test01:s1==s2 s1 equals s2test02:s1! =s2 s1 equals s2test03:s1=s2 s1 equals s2 truetrue
Not to be continued ...
= = and equals in Java