on equals and = = in Java

Source: Internet
Author: User

on equals and = = in Java

When you are learning Java, you may often encounter the following code:

1 String str1 = new String ("Hello"), 2 string str2 = new String ("Hello"), 3         4 System.out.println (STR1==STR2), 5 System.ou T.println (Str1.equals (str2));

Why is the output of lines 4th and 5th different? What is the difference between = = and the Equals method? If this problem is not clear when you are learning Java, you will cause some low-level errors when you write code later. Join us today to learn about the differences between = = and the Equals method.

I. What does the relational operator "= =" Compare?

The following sentence is excerpted from the book "Java Programming thought":

"Relational operators generate a Boolean result that calculates the relationship between the operands ' values."

This sentence seems simple, understanding or needs to be carefully realized. The simple point, = = is used to compare the value is equal. Let's look at a few examples below:

public class Main {    /**     * @param args */public    static void Main (string[] args) {        //TODO Auto-generat Ed method stub                int n=3;        int m=3;                System.out.println (n==m);                String str = new string ("Hello");        String str1 = new String ("Hello");        String str2 = new String ("Hello");                System.out.println (STR1==STR2);                str1 = str;        str2 = str;        System.out.println (STR1==STR2);    }}

The output is true false true

N==m The result is true, it is easy to understand that variable N and variable m store values of 3, which are definitely equal. And why are the results of the two comparisons between str1 and str2 different? To understand this, you just need to understand the difference between a basic data type variable and a non-basic data type variable.

There are 8 basic data types in the middle of Java:

Float type: float (4 byte), double (8 byte)

Integer: Byte (1 byte), short (2 byte), int (4 byte), Long (8 byte)

Character type: char (2 byte)

Boolean: Boolean (JVM specification does not explicitly specify the amount of space it occupies, only the literal value "true" and "false" is specified)

For variables of these 8 basic data types, variables directly store "value", so when comparing by using the relational operator = =, the comparison is "value" itself. Note that both floating-point and integral types are signed, and Char is an unsigned type (the char type has a value range of 0~2^16-1).

This means, for example:

int n=3;

int m=3;

Both the variable n and the variable m are stored directly in the "3" value, so the result is true when compared with = =.

For variables of non-basic data types, variables in some books are referred to as reference types. For example, the above str1 is a variable of a reference type, and a variable of reference type stores not the "value" itself, but the address of its associated object in memory. For example, the following line of code:

String str1;

This statement declares a variable of a reference type, at which point it is not associated with any object.

Instead, a new String ("Hello") is used to produce an object (also known as an instance of the class String) and bind the object to STR1:

str1= New String ("Hello");

So str1 points to an object (many places also refer to str1 as a reference to the object), when the variable str1 stores the memory address of the object it points to, not the "value" itself, that is, the string "hello" that is not stored directly. The references in this are very similar to the pointers in C + +.

Therefore, when the first comparison is made with = = for str1 and str2, the result is false. So they point to different objects, which means they actually store different memory addresses.

In the second comparison, both STR1 and str2 point to the object that Str points to, and the resulting result is undoubtedly true.

Two. What is the comparison of equals?

The Equals method is a method in the base class object, so there is a method for all classes that inherit from object. For a more intuitive understanding of the role of the Equals method, look directly at the implementation of the Equals method in the object class.

The source path for this class is: Object.java under the Java.lang path of the C:\Program files\java\jdk1.6.0_14 src.zip (depending on the personal JDK installation path).

The following is the implementation of the Equals method in the object class:

  

Obviously, in the object class, the Equals method is used to compare the two-object references for equality, that is, to point to the same object.

But some friends will have questions, why the following section of the output of the code is true?

public class Main {    /**     * @param args */public    static void Main (string[] args) {        //TODO Auto-generat Ed method Stub                String str1 = new String ("Hello");        String str2 = new String ("Hello");                System.out.println (Str1.equals (STR2));}    }

To know exactly, you can look at the specific implementation of the Equals method of the string class, also under this path, String.java is the implementation of the String class.

The following is a concrete implementation of the Equals method in the String class:

As you can see, the string class overrides the Equals method to compare whether the strings stored by the pointed string object are equal.

Other classes, such as Double,date,integer, have overridden the Equals method to compare whether the object being stored by the pointer is equal.

To summarize, say:

1) for = =, if the variables that are acting on the base data type are directly compared to the value of their stored values for equality;

If you are acting on a variable of a reference type, the address of the object to which you are pointing is compared

2) for the Equals method, note that the Equals method cannot act on a variable of the base data type

If the Equals method is not overridden, the address of the object to which the variable of the reference type is to be compared;

Classes such as String, date, and so on have overridden the Equals method to compare the contents of the object being pointed to.

on equals and = = in Java

Related Article

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.