A brief description of the difference between the Equals () method and = = in Java

Source: Internet
Author: User

The main differences between = = and equals are:

= =:

    • = = is often used to compare native types (base data types): Byte,short,char,int,long,float,double,boolean, which compares their values.
    • If you compare two objects with = =, the memory addresses of the two objects are compared. Therefore, unless it is the same new object, the comparison result is true, and the different objects are compared with = = False.
    • However, for objects that have a caching mechanism, such as an integer, Byte, short, Long, character object (known to these objects at this time), in its cache scope, you can compare the correct result with = =. The specific range is: Integer, Byte,short,long fixed range is:-128 to 127;character fixed range is 0 to 127. Except the Integer can be changed by the parameter range, the others are not. Specifically, I forwarded the blog to understand the Java integer cache policy "Go"

equals () Method:

A method of equals is defined in the base class in object, the initial behavior of this method is to compare the memory address of the object, the source code is as follows:

 Public Boolean equals (Object obj) {        return ( this = = obj);}

Therefore, for an object that has not overridden the Equals () method, the comparison with Equals () is the same as = = compared to the memory address

However, in some class libraries This method is overridden, such as string,integer,date in these classes, where equals has its own implementation, and is no longer a comparison class in the heap memory of the storage address. Therefore, when we create our own classes, to compare this class, be sure to override the Equals () method

A brief description of the difference between the Equals () method and = = 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.