equals and == in Java

I believe that you often encounter strings using equals and == to compare, and interpret the output as true or false.

    In fact, as long as you understand it, this kind of question is so easy! ! !

    Let's take a look at an example

public class day01_6 {
    public static void main(String[] args) {
        String str1 = new String("111");
        String str2 = "111";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));
    }
}

    I believe you all know the answer, that is false and true. why

    First == is used to compare values. And what is the value of str1 and str2, that is the address value

    Obviously str1 points to the heap, str2 points to the method area, the addresses are different, so return false

    So what does equals compare? Let's see how Object is defined.

public boolean equals(Object obj) {
    return (this == obj);
}

    Duh, they are also comparing address values.

    So, without overriding the class's equals, they are all comparing address values.

    The String class rewrites the equals method to compare the contents of the strings. Obviously, the two strings are both 111, so they are equal.

The conclusion is:

    1. When using == comparison, if it is a basic data type, the size of their value is compared, and for reference types, they compare their address values

    2. When using equals comparison, only reference types can be compared. If the class does not override the equals method, then their address values ​​are compared. If the equals method is overridden, the comparison is performed according to the definition of the equals method.

Guess you like

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