Difference between equals and = in Java

Source: Internet
Author: User

Equals is equivalent when comparing the attribute values of two objects:

String str1 = "ASC"; // store it in the stack

String str2 = new string ("ASC ");

Str1.equals (str2) // true

= Equal when comparing two objects, that is, when two references point to the same object

String str3 = new string ("ASC ");

String str4 = new string ("ASC ");

String str5 = str3;

At this time: str3 = str4 false

Str5 = str3 true

The above content has a problem: it is only valid for the string, because the string overload the equals method.

Java data types can be divided into two types:
1. The basic data type, also known as the original data type. Byte, short, Char, Int, long, float, double, Boolean
The comparison between them applies the double equal sign (=) to compare their values.
2. Composite data type (class)
When they use (=) for comparison, they compare their storage addresses in the memory, so unless they are the same new object, their comparison result is true, otherwise the comparison result is false. All classes in Java are inherited from the base class object. An equals method is defined in the base class of the object. The initial behavior of this method is to compare the memory location of the object.
But in some class libraries, this method is overwritten, such as string, integer, and date. Among these classes, equals has its own implementation, instead of the storage address of the comparison class in the heap memory.
For equals comparison between composite data types, if the equals method is not overwritten, the comparison between them is based on the address value of their storage location in the memory, because the equals method of the object is compared with the binary equal sign (=), the comparison result is the same as that of the binary equal sign (=.

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.