Differences between equals and =, =, and equals
I. = and equals
1. = is an operator
2. equals is a String object method.
There are two types of comparison
1. Comparison of Basic Data Types
2. Comparison of referenced objects
1. Comparison of Basic Data Types
= Both equals and equals compare whether the values are equal. If they are equal, true is used; otherwise, false is used.
2. Comparison of referenced objects
= And equals both compare whether the addresses in the stack memory are equal. If they are equal, true is used; otherwise, false is used.
Note:
1. String is a special reference data type. = compares whether the reference addresses of String objects are the same, and equals compares whether the stack content is consistent.
String ss = new String ("abc ");
String sss = new String ("abc ");
If (ss = sss ){
System. out. println ("ss = sss is true ");
}
If (ss. equals (sss )){
System. out. println ("ss equals sss is true ");
}
Console output:
Ss! = Sss
Ss equals sss
It indicates that the memory address of ss and sss in the stack is different, but the content in the stack is the same.
String ss = new String ("abc ");
String ssss = ss;
// Determine whether the reference addresses of ss and ssss in the stack are the same
If (ss = ssss ){
System. out. println ("ss = ssss ");
} Else {
System. out. println ("ss! = Ssss ");
}
// Determine whether the content of ss and ssss In the heap is the same
If (ss. equals (ssss )){
System. out. println ("ss equals ssss ");
} Else {
System. out. println ("ss not equals ssss ");
}
Console output:
Ss = ssss
Ss equals ssss
This indicates that ss and ssss are the same object, and they have the same content in the heap.
2. Comparison of referenced objects
TestBean obj1 = new TestBean ();
TestBean obj2 = new TestBean ();
TestBean obj3 = obj1;
If (obj1 = obj2 ){
System. out. println ("obj1 = obj2 ");
} Else {
System. out. println ("obj1! = Obj2 ");
}
If (obj1 = obj3 ){
System. out. println ("obj1 = obj3 ");
} Else {
System. out. println ("obj1! = Obj3 ");
}
Console output:
Obj1! = Obj2
Obj1 = obj3
It indicates that obj1 and obj2 are not the same object and the reference addresses in the stack are different.
Obj1 and obj3 are the same objects, and the reference addresses in the stack are the same.
Ii. Difference Between = and equals =
= Indicates a value, that is, = the value on the right is assigned to the variable on the left. Equals and = indicate the operation