The data types in Java can be divided into two categories:
1. Basic data types, also known as raw data types. Byte,short,char,int,long,float,double,boolean;
The comparison between them should be "= =" and compare their values.
2. Composite data types are reference data types (classes)
When they are compared with (= =), they are compared to their memory address, so unless it is the same new object, they compare the result is true, otherwise the result of the comparison is false. All classes in Java inherit from the base class object, where a equals method is defined in the base class in object:
The initial behavior of this method is to compare the memory address of the object, but in some class libraries This method is overwritten, such as string,integer,date in these classes where equals has its own implementation, rather than the comparison class in the heap memory of the storage address. For the equals comparison between composite data types, the comparison between them is based on the address value of the location in memory where the Equals method is not covered, because the Equals method of object is compared with the double equals sign (= =). So the result of the comparison is the same as the double equals sign (= =).
Compile and run the program, output: S1 = = S2; Description: S1 and S2 refer to the same string object-"Monday"
A little change to the program, it will be more strange to find:
We will create the S2 with the new operator. Program output: S1! = s2 S1 equals s2 Description: S1,s2 references two "Monday" string objects respectively.
Originally, the program will create a string buffer when running, when using S2 = "Monday" expression is to create a string, the program first in this string buffer pool to find the same object. In the first program, S1 is first placed in the pool, so when S2 is created, the program finds a S1 with the same value, so the S2 reference points to the object "S1" that Monday refers to. In the second paragraph of the program, the new operator is used, which explicitly tells the program: "I want a new one!" Don't be old! "So a new" Monday "string object is created in memory. Their values are the same, but the locations are different, one swimming in the pool and one resting on the shore. So it seems that the real waste of a resource, obviously the same, but to separate.
Change the program again:
This time join: S2 = S2.intern ();
Program output: S1 = = s2 S1 equals s2 Originally, Java.lang.String's Intern () method, "ABC". The return value of the Intern () method is also the string "ABC", which appears to be of no use to the method. But in fact, it did a little trick: Check the string pool for the existence of a string "abc", if present, return the string in the pool, if it does not exist, the method will add "ABC" to the string pool, and then return its reference.
The difference between equals and = = in Java