Java syntax ---- difference between equals and = in Java ---- javaequals

Source: Internet
Author: User

Java syntax ---- difference between equals and = in Java ---- javaequals

[Statement]

Reprinted, but keep the original source of the article → _ →

Life One: http://www.cnblogs.com/smyhvae/

Source: http://www.cnblogs.com/smyhvae/p/3929585.html

Contact: smyhvae@163.com

 

[Body]

When I was learning the Android and Java languages, I always met the "equals" and "=" characters. I always felt similar. In fact, there are still some differences, today, I want to thoroughly understand them.

1. The data type and the meaning of "=" in java:

  • Basic data type (also called raw data type): byte, short, char, int, long, float, double, boolean. The comparison between them applies the double equal sign (=) to compare their values.
  • Composite data types (classes): when they use (=) for comparison, they compare the storage addresses in the memory (specifically, the heap memory address ).

NOTE: For the second type, the comparison result is true unless it is a new object. Otherwise, the comparison result is false. Because every new time, heap memory space will be re-opened.

 

Ii. equals () method introduction:

All classes in JAVA are inherited from the Super Class Object. An equals method is defined in the Object class. The initial behavior of this method is to compare the memory address of the Object, however, in some class libraries, this method is rewritten, such as String, Integer, and Date. Among these classes, equals has its own implementation, instead of comparing the storage addresses of classes in the heap memory.
Therefore, for equals comparison between composite data types, if the equals method is not overwritten, the comparison between them is the address value of the storage location in the memory, the result is the same as that of the dual equal sign (=). If the result is rewritten, the result is based on the requirements of the write operation.

 

Iii. equals () method of the String class:

Now let's take the String class as an example:

We found the String class in the \ src \ java \ lang directory and found that the equals method was rewritten as follows:

 1     public boolean equals(Object anObject) { 2         if (this == anObject) { 3             return true; 4         } 5         if (anObject instanceof String) { 6             String anotherString = (String)anObject; 7             int n = value.length; 8             if (n == anotherString.value.length) { 9                 char v1[] = value;10                 char v2[] = anotherString.value;11                 int i = 0;12                 while (n-- != 0) {13                     if (v1[i] != v2[i])14                         return false;15                     i++;16                 }17                 return true;18             }19         }20         return false;21     }

The code above shows that the rewritten equals () method in the String class actually compares the content of two strings. Next we will look at the comparison of the String class through the actual code.

1. The example code is as follows:

1 public class StringDemo {2     public static void main(String[] args) {3         String s1 = "Hello";4         String s2 = "Hello";5         System.out.println(s1 == s2);   // true6     }7 }

In the code above, use "=" to compare s1 and s2, and return true.

2. If you change the program a little, you may find it strange:

1 public class StringDemo {2 public static void main (String args []) {3 String str1 = "Hello ";4 String str2 = new String ("Hello ");5 String str3 = str2; // pass the reference6 System. out. println (str1 = str2); // false7 System. out. println (str1 = str3); // false 8 System. out. println (str2 = str3); // true 9 System. out. println (str1.equals (str2); // true10 System. out. println (str1.equals (str3); // true11 System. out. println (str2.equals (str3); // true12} 13}

In the code at the top 4th lines, we have a new object. When we compare s1 and s2 with "=", the returned result is false. We use "equals" to compare s1 and s2, the returned result is true.

To analyze the above Code, we must first analyze the heap memory controls and stack memory space, which is very important:

After reading the above figure and combining the above code, you can see it at a glance. Now we can give ourselves an interview question:

Interview question: What is the difference between "=" and "equals ()" in the string comparison?

  • =: Compare the values of the memory addresses of two strings;
  • Equals (): Compares the content of two strings.

Equals () will be used for subsequent equality Determination of strings ().

3. Change the program again:

1 public class ObjectDemo{2     public static void main(String[] args) {3         String s1 = "Hello";4         String s2 = new String("Hello");5         s2 = s2.intern();6         System.out.println(s1 == s2);       //  true7         System.out.println(s1.equals(s2));  //  true8     }9 }

Java. lang. the intern () method of String "abc ". the Return Value of the intern () method is still the string "abc". On the surface, it seems that this method is useless. But in fact, it performs a small action: Check whether there is a string such as "abc" in the string pool. If yes, the string in the pool is returned; if not, this method adds "abc" to the string pool and then returns its reference.

 

4. Compare the values of two objects:

The Code is as follows:

1 public class ObjectDemo {2 public static void main (String args []) {3 Student student1 = new Student ("Life 1", 22, "Chengdu "); 4 Student student2 = new Student ("Life 1", 22, "Chengdu"); 5 System. out. println (student1 = student2); 6 System. out. println (student1.equals (student2); 7} 8} 9 class Student {10 private String name; 11 private int age; 12 private String address; 13 public Student (String name, int age, String ad Dress) {14 this. name = name; 15 this. age = age; 16 this. address = address; 17} 18 // rewrite the equals method in the Object class (compare the values of the two objects) 19 public boolean equals (Object obj) {20 // if the memory address is equal, it must be the same object, so you do not need to compare the attribute values of the two objects 21 if (this = obj) {22 return true; 23} 24 // determine whether obj is a Baboon instance 25 if (obj instanceof Student) {26 Student B = (Student) obj; // force convert 27 // determine whether the attribute values of the two objects are equal 28 if (! This. name. equals (B. name) {29 return false; 30} 31 else if (this. age! = B. age) {32 return false; 33} 34 else if (this. address! = B. address) {35 return false; 36} 37 return true; 38} else {39 return false; 40} 41} 42}

In the above Code, first determine whether the passed object is equal to the address of the current object. If it is equal, it must be the same object. Because the passed parameters are of the Object type, any Object can receive them. Once it is received, the Object type will be transformed down and then judged.

 

[Reference]

Refer to blog:

Http://www.cnblogs.com/zhxhdean/archive/2011/03/25/1995431.html

Http://www.cnblogs.com/zhxhdean/archive/2011/03/26/1996468.html

This is also a video of instructor Li Xinghua.


What is the difference between "equals" and "=" in JAVA?

The = number compares the address value of an object in the memory,
For example, two string objects
String s1 = new String ("str ");
String s2 = new String ("str ");
If the = character is used for comparison, false is returned. Because two objects are created, their locations in the memory are different.

Equals is complex. It is a method in the java. lang. Object Class. Because all classes in java inherit from objects by default, all classes have this method.

This is written in the source code of the Object class.
Public boolean equals (Object obj ){
Return (this = obj );
}
It also uses the = sign to compare the memory addresses. However, this method is overwritten in many java classes, such as String.
Public boolean equals (Object anObject ){
If (this = anObject ){
Return true;
}
If (anObject instanceof String ){
String anotherString = (String) anObject;
Int n = count;
If (n = anotherString. count ){
Char v1 [] = value;
Char v2 [] = anotherString. value;
Int I = offset;
Int j = anotherString. offset;
While (n --! = 0 ){
If (v1 [I ++]! = V2 [j ++])
Return false;
}
Return true;
}
}
Return false;
}

If the = character in the String is not equal, a comparison of the value is performed.
Therefore, the specific function of the equals method depends on how the current class is implemented to override the method in the parent class. If this method is not overwritten, it is equivalent to =.

In java, equals and = are different.

Equals checks whether the content of the two objects is the same
= Compare whether two objects are the same object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.