Talking about equals and == in Java

Talking about equals and == in Java

  When 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.out.println(str1.equals(str2));

  Why is the output on line 4 and line 5 different? What is the difference between == and equals methods? If you don't understand this problem when you first learn Java, it will lead to some low-level mistakes when you write code later. Today, let's learn about the difference between == and equals methods.

1. What does the relational operator "==" compare?

  The following sentence is excerpted from the original words of the book "Java Programming Ideas":

  "Relational operators produce a boolean result, and they compute the relationship between the values ​​of the operands".

  This sentence seems simple, but it needs to be understood in detail. To put it simply, == is used to compare values ​​for equality. Here are a few examples:

copy code
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated 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);
    }

}
copy code

  The output is true false true

  The result of n==m is true, which is easy to understand. The values ​​stored in variable n and variable m are both 3, which must be equal. And why the results of the two comparisons of str1 and str2 are different? To understand this, you only need to understand the difference between primitive data type variables and non-basic data type variables.

  There are 8 basic data types in Java midstream:

  Floating point: float(4 byte), double(8 byte)

  整型:byte(1 byte), short(2 byte), int(4 byte) , long(8 byte)

  Character type: char(2 byte)

  Boolean: boolean (The JVM specification does not specify the size of the space it occupies, only that it can only take literal values ​​"true" and "false")

  For the variables of these 8 basic data types, the variable directly stores the "value", so when the relational operator == is used for comparison, the "value" itself is compared. It should be noted that both floating-point and integer types are signed types, while char is an unsigned type (the value range of char type is 0~2^16-1).

  That is, for example:

  int n=3;

  int m=3; 

  Both variable n and variable m directly store the value of "3", so the result is true when using == to compare.

  For variables of non-primitive data types, in some books it is called a variable of reference type. For example, the above str1 is a variable of reference type. The variable of reference type stores not the "value" itself, but the address in memory of the object associated with it. For example the following line of code:

  String str1;

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

  And use new String("hello") to generate an object (also known as an instance of the class String), and bind this object to str1:

  str1= new String("hello");

  Then str1 points to an object (str1 is also referred to as a reference to an object in many places), at this time, the variable str1 stores the storage address of the object it points to in memory, not the "value" itself, which means that it is not The directly stored string "hello". References here are very similar to pointers in C/C++.

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

  In the second comparison, both str1 and str2 point to the object pointed to by str, so the result obtained is undoubtedly true.

2. What does equals compare?

  The equals method is a method in the base class Object, so all classes that inherit from Object will have this method. In order to understand the role of the equals method more intuitively, look directly at the implementation of the equals method in the Object class.

  The source path of this class is: Object.java under the java.lang path of src.zip of C:\Program Files\Java\jdk1.6.0_14 (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 whether the references of two objects are equal, that is, whether they point to the same object.

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

copy code
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String str1 = new String("hello");
        String str2 = new String("hello");
        
        System.out.println(str1.equals(str2));
    }
}
copy code

  To know what is going on, you can look at the specific implementation of the equals method of the String class. Also in this path, String.java is the implementation of the String class.

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

  It can be seen that the String class rewrites the equals method to compare whether the strings stored in the pointed string object are equal.

  Some other classes such as Double, Date, Integer, etc., have overridden the equals method to compare the contents of the pointed object to be equal.

  In conclusion:

  1) For ==, if it acts on a variable of a basic data type, it directly compares its stored "value" for equality;

    If acting on a variable of reference type, the address of the pointed-to object is compared

  2) For the equals method, note: the equals method cannot act on variables of basic data types

    If the equals method is not overridden, the address of the object pointed to by the variable of the reference type is compared;

    If classes such as String and Date override the equals method, the content of the pointed object is compared.

 

Author: Haizi
    

Talking about equals and == in Java

  When 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.out.println(str1.equals(str2));

  Why is the output on line 4 and line 5 different? What is the difference between == and equals methods? If you don't understand this problem when you first learn Java, it will lead to some low-level mistakes when you write code later. Today, let's learn about the difference between == and equals methods.

1. What does the relational operator "==" compare?

  The following sentence is excerpted from the original words of the book "Java Programming Ideas":

  "Relational operators produce a boolean result, and they compute the relationship between the values ​​of the operands".

  This sentence seems simple, but it needs to be understood in detail. To put it simply, == is used to compare values ​​for equality. Here are a few examples:

copy code
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated 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);
    }

}
copy code

  The output is true false true

  The result of n==m is true, which is easy to understand. The values ​​stored in variable n and variable m are both 3, which must be equal. And why the results of the two comparisons of str1 and str2 are different? To understand this, you only need to understand the difference between primitive data type variables and non-basic data type variables.

  There are 8 basic data types in Java midstream:

  Floating point: float(4 byte), double(8 byte)

  整型:byte(1 byte), short(2 byte), int(4 byte) , long(8 byte)

  Character type: char(2 byte)

  Boolean: boolean (The JVM specification does not specify the size of the space it occupies, only that it can only take literal values ​​"true" and "false")

  For the variables of these 8 basic data types, the variable directly stores the "value", so when the relational operator == is used for comparison, the "value" itself is compared. It should be noted that both floating-point and integer types are signed types, while char is an unsigned type (the value range of char type is 0~2^16-1).

  That is, for example:

  int n=3;

  int m=3; 

  Both variable n and variable m directly store the value of "3", so the result is true when using == to compare.

  For variables of non-primitive data types, in some books it is called a variable of reference type. For example, the above str1 is a variable of reference type. The variable of reference type stores not the "value" itself, but the address in memory of the object associated with it. For example the following line of code:

  String str1;

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

  And use new String("hello") to generate an object (also known as an instance of the class String), and bind this object to str1:

  str1= new String("hello");

  Then str1 points to an object (str1 is also referred to as a reference to an object in many places), at this time, the variable str1 stores the storage address of the object it points to in memory, not the "value" itself, which means that it is not The directly stored string "hello". References here are very similar to pointers in C/C++.

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

  In the second comparison, both str1 and str2 point to the object pointed to by str, so the result obtained is undoubtedly true.

2. What does equals compare?

  The equals method is a method in the base class Object, so all classes that inherit from Object will have this method. In order to understand the role of the equals method more intuitively, look directly at the implementation of the equals method in the Object class.

  The source path of this class is: Object.java under the java.lang path of src.zip of C:\Program Files\Java\jdk1.6.0_14 (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 whether the references of two objects are equal, that is, whether they point to the same object.

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

copy code
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String str1 = new String("hello");
        String str2 = new String("hello");
        
        System.out.println(str1.equals(str2));
    }
}
copy code

  To know what is going on, you can look at the specific implementation of the equals method of the String class. Also in this path, String.java is the implementation of the String class.

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

  It can be seen that the String class rewrites the equals method to compare whether the strings stored in the pointed string object are equal.

  Some other classes such as Double, Date, Integer, etc., have overridden the equals method to compare the contents of the pointed object to be equal.

  In conclusion:

  1) For ==, if it acts on a variable of a basic data type, it directly compares its stored "value" for equality;

    If acting on a variable of reference type, the address of the pointed-to object is compared

  2) For the equals method, note: the equals method cannot act on variables of basic data types

    If the equals method is not overridden, the address of the object pointed to by the variable of the reference type is compared;

    If classes such as String and Date override the equals method, the content of the pointed object is compared.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325072810&siteId=291194637