The difference between = = and equals in Java

Source: Internet
Author: User

= = and the essence of equals.

When comparing variables with "= =" in Java, the system uses the values stored in the "stack" of variables as the basis for comparison.

The base data type is stored in the stack as its content value, and the object type is the address that is stored in the stack, which points to the object in the heap.

The object class in the Java.lang package has the public boolean equals (Object obj) method, which compares two objects for equality.

The Equals method of other objects returns true only if the object contents of the two references to the comparison are the same.

In short, the "= =" and "! =" comparisons are addresses. You can also think that "= =" and "! =" Compare object handles, whereas Equals () compares object content. Or, "= =" and "! =" Compare the contents of "stack", while Equals () compares the contents of "heap".

= = operator . Specifically used to compare the values of two variables are equal, that is, the memory used to compare the variables stored in the same value, to compare two basic types of data or two reference variable is equivalent, can only use the = = operator.

The basic data type for Java is (Char,byte,short,int,long,float,double,boolean).

If the data that a variable points to is object type, then it involves two blocks of memory, the object itself occupies a piece of memory (for memory), and the variable itself occupies a piece of memory, for example, object obj = new object () variable obj is a memory, new object () is a memory , the data stored in the memory corresponding to the variable is the first address of the memory that the object occupies. For variables that point to the memory of the object, if you want to compare whether the two variables point to the same object, that is to see if the two variables correspond to the value of the memory is equal, this time you need to use the = = operator to compare.

The differences in the formation of constructors. for string and integer, because of their unique way of creating objects. Using constructors and not using constructors to get an object, the = = Method comparison produces different results. String a = "abc"; String B = "abc"; At this point a==b gets the result as true. String a = new string ("abc"); String b = new String ("abc"), at which time the a==b results are false. Integer a = 1; Integer B = 1, at which point the result of A==b is true. Integer a = new integer (1); Integer b = new Integer (1), at which time the a==b results are false.

In fact, we can also make it easier to understand = = The actual operation of the memory, the actual execution is approximate to the basic type comparison.

String object and string connection pool:

The inclusion of text in quotation marks is a way of creating objects that are unique to the string class. But the result of "= =" Returned is true, why? Because within the JVM, there is a string pool, which holds many string objects and can be shared. So it improves efficiency. The string pool is maintained by the strings class, and we can call The Intern () method to access the string pool. When you use quotation marks to create an object, the object you create is added to the string pool. If you want to create the next string object, the JVM will first look in the string pool, if there is a corresponding string object, Returns a reference to an object that already exists, to the object reference to be created. If it does not exist, a new object is created and a new object reference is returned to the object reference to be created. The above paragraph may be more difficult to understand. The code understands that str2 and str1 are two object references, and points to the same object. so ' = = ' returns True.

Only the text creation object inside the quotation marks will put the created object into the string pool. The string object created by string str = new String ("abc") is not put into a string pool. Therefore, the performance of text-creation objects within quotation marks is better than the performance of subsequent methods of creating string objects.

String str1 = "abc";

String str2 = "abc";

String STR3 = STR1+STR2; This method of creation is not put into a string pool.

String STR4 = str1+ "CD"; This method of creation is not put into a string pool.

String STR5 = "AB" +STR2; This method of creation is not put into a string pool.

String STR6 = "AB" + "CD"; This is created in a string pool. This situation actually creates 1 objects, ABCD "1 objects

String STR7 = "ABCD";

System.out.println (STR1==STR2); Back to Ture

System.out.println (STR6==STR7); Back to Ture

another question:

Let's start by looking at a Java code:

String Str=new string ("abc");

This is often followed by this code, that is, how many string objects does this line of code create? I believe we are not unfamiliar with this problem, the answer is well-known, 2. Let's start with this question and review some of the Java knowledge associated with creating a string object.

We can think of this line of code as String str, =, "abc" and new String () four. String str simply defines a variable of type string named STR, so it does not create an object; = is initialized to the variable str, assigns a reference to an object (or a handle) to it, and apparently does not create an object; now only the new string ("abc") is left. The So why can new string ("abc") be considered "ABC" and new String ()? Let's take a look at the constructor of the string we called:

Java code

public string (string original) {
Other code ...
}
As we all know, there are two ways to create an instance of a Class (object):
We created an object using the above constructor method that called the string class with new, and assigned its reference to the STR variable. At the same time, we notice that the called constructor method accepts parameters that are also a string object, which is "ABC".

Using new to create an object is the Newinstance method that calls the class class and uses the reflection mechanism to create the object.

equals method . To compare the contents of two separate objects is the same as to compare two people's looks are the same, it compares the two objects are independent. For example, for the following code:

String A=new string ("foo");

String B=new string ("foo");

Two new statements create two objects, and then with a, B, the two variables point to one of the objects, which is two different objects, their first address is different, that is, the values stored in a and a are not the same, so the expression a==b returns False, and the contents of the two objects are the same, so , the expression a.equals (b) returns True.

In the actual development, we often have to compare the delivery of the string content is equal, many people do not pay attention to the use of = = to compare, this is wrong, there are a large number of such errors. Remember that the comparison of strings is basically using the Equals method.

If a class does not define the Equals method . It inherits the Equals method of the object class, and the implementation code for the Equals method of the object class is as follows:

Boolean equals (Object o) {

return this==o;

}

This means that if a class does not define its own Equals method, its default Equals method (inherited from the object class) is using the = = operator, and whether the object pointed to by the two variables is the same object, when using equals and using = = will get the same result. If the comparison is two independent objects, the total return is false. If you are writing a class that wants to compare the contents of the two instance objects created by the class, then you must override the Equals method, and write your own code to determine what the contents of the two objects can be considered to be the same.

Example code :

public class Test {


public static void Main (string[] args) {


Integer p = 1;


Integer q = 1;


Integer i = new integer (1);


Integer j = new Integer (1);


if (p = = q) {


System.out.println ("integer:p = = q"); Actual results


} else {


SYSTEM.OUT.PRINTLN ("Integer:p! = q");


}


if (P.equals (q)) {


System.out.println ("Integer:p.equals (q)"); Actual results


} else {


System.out.println ("Integer:p.equals (q)");


}


if (i = = j) {


System.out.println ("int:i = = j");


} else {


SYSTEM.OUT.PRINTLN ("Int:i! = j"); Actual results


}


if (I.equals (j)) {


System.out.println ("Integer:i.equals (j)");//Actual results


} else {


System.out.println ("Integer:!i.equals (j)");


}


String a = "abc";


String B = "abc";


String c = new String ("abc");


String d = new String ("abc");


if (a = = b) {


SYSTEM.OUT.PRINTLN ("ABC object equals"); Actual results


} else {


SYSTEM.OUT.PRINTLN ("ABC objects are not Equal");


}


if (A.equals (b)) {


System.out.println ("ab equals"); Actual results


} else {


SYSTEM.OUT.PRINTLN ("Ab Not Equal");


}


if (C.equals (d)) {


SYSTEM.OUT.PRINTLN ("CD equal"); Actual results


} else {


SYSTEM.OUT.PRINTLN ("CD is not Equal");


}


if (c = = d) {


SYSTEM.OUT.PRINTLN ("CD object Equal");


} else {


SYSTEM.OUT.PRINTLN ("CD Object Not Equal"); Actual results

}

}

}



The difference between = = and equals in Java

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.