Equal and "=" both mean equal, but they differ greatly in actual equality determination.
Let's take a look at an example.
1 Public class upload test { 2 Public static Void Main (string [] ARGs ){ 3 String str1 = "ABCD" ; 4 String str2 = "ABCD" ; 5 String str3 = New String ("ABCD"); 6 7 System. Out. println (str1 = Str2 ); 8 System. Out. println (str1 = Str3 ); 9 System. Out. println (str1.equals (str3 )); 10 } 11 }
AboveCodeThree string variables are defined in, and their values are all "ABCD". In theory, they should all be true. But in fact, the result is
True
False
True
The second is false because str1 and str3 point to different objects.
= It is used to compare the actual values of the basic data types to determine whether they are the same, but used to compare the reference types. It is to compare whether the two referenced addresses are the same, that is, whether to point to the same object. The string created by using new string () generates an object separately, so str1 and str3 do not point to the same object. The double quotation mark expression in Java creates a String object.
The EQUAL () method is the java. Lang. Object method. That is to say, all Java classes will have this method. It can be overwritten and overwritten to determine whether two objects are equal in a custom way. The default mode is the same as =. However, java. Lang. String classes are different and cannot be inherited. Its equal () method is used to compare whether the string sequence is completely equal.
For example:
1 Public Class Student { 2 Private String name; 3 Private Int Age; 4 5 Public Student (string name, Int Age ){ 6 This . Name = Name; 7 This . Age = Age; 8 } 9 Public Boolean Equals (Object object ){ 10 Student = (Student) object; 11 Return This . Name. Equals (student. Name )&& This . Age = Student. Age; 12 } 13 } 14 15 Public Class Using test { 16 17 Public Static Void Main (string [] ARGs ){ 18 Student stud1 = New Student ("liming", 11 ); 19 Student stud2 = New Student ("liming", 11 ); 20 System. Out. println (stud1.equals (stud2 )); 21 } 22 23 }
The execution result is true.