Today, when writing expression evaluation, we found the Equals and ==| |! = and!equals () are not the same.
I searched the internet for knowledge about this and then made a summary below:
There are two kinds of data types in Java:
Basic data type (Primitive Types)
of which: Byte,short,char,int,long,double,boolean
They are compared in three ways (= =), (! =), (. Equals ()).
Composite data type (Composite Types)
Where: String, array, General class, interface, etc.
Below I rely mainly on string to compare = = vs. equals ()
When they are compared using the = = operation, they compare their in- memory addresses.
When they use. Equals (), they compare their values.
Not much to say, first on the code
public class test{public static void main (string args[]) { string str1 = "Test"; String str2 = "Test"; System.out.println (STR1==STR2);
System.out.println (Str1.equals (str2)); } }
After running, output:
True
True
Let's make a few changes to the program and find
public class test{public static void Main (string[] args) { String str1 = "Test"; String str2 = new String ("Test"); System.out.println (STR1==STR2); System.out.println (Str1.equals (STR2));} }
After running, the output
False
True
What is all this for?
Here we refer to the string buffer pool
The program will create a string buffer pool at run time, in the first program, STR1 and str2 are equal to "Test", the program will first look for objects with the same value in this string buffer pool, because str1 that statement is executed first, so str2 in later creation, An address with the same value str1 is used, so the STR1==STR2 expression returns true;
But the second program is different, because the second program uses the New keyword, and in the space it assigns a str2 to the address, so the STR1==STR2 returns false.
Finally, make a simple sublimation
Object in Java is the base class for all classes, defined in object as the. Equals () method, which is itself used to compare the address of an object. But in the String,integer,date class, the. Equals () method is overridden, so when we use it, the function is no longer their address, but their value.
The difference between equals and = = in Java