[Interview Frequently Asked Questions]: The difference between equals and == in Java

1. "=="

== The comparison is stored in the variable (stack) memoryThe (heap) memory address of the object, Used to determine whether the addresses of two objects are the same, that isDoes it refer to the same object. The comparison is the pointer operation in the true sense.
1. The comparison is whether the operands at both ends of the operator are the same object.
2. The operands on both sides must be of the same type (it can be between parent and child classes) in order to compile and pass.
3. The comparison is the address. If it is a comparison of specific Arabic numerals, the value is equal to true, such as:
int a=10 and long b=10L and double c=10.0 are the same (true), because they are both Point to the heap at address 10.

	@Test
    public void test1(){
    
    
        /**
         *   == 比较的是地址,如果是具体的阿拉伯数字的比较,值相等则为true,如:
         *   int a=10 与 long b=10L 与 double c=10.0都是相同的(为true),因为他们都指向地址为10的堆。
         */

        int a=10;
        long b=10L;
        double c=10.0;
        System.out.println(a==b);	//true
        System.out.println(b==c);	//true
        System.out.println(a==c);	//true
    }

Two, "equals"

equals is used to compare two objectsWhether the contents are equal, Since all classes are inherited from java.lang.Object class, they are applicable to all objects. If the method is not covered, the method in the Object class is still called, and the equals method in Object returns But it is the judgment of ==.

 	@Test
    public void test2(){
    
    
        String a = "1";
        System.out.println("1".equals(a));

    }

Three, summary

1. When all comparisons are equal, equals are used and when comparing constants,Constants are written in front, Because the equals object of the object may be null, a null pointer appears.
2. In Ali’s code specification, only equals is used. Ali plug-in will recognize it by default and can be quickly modified. It is recommended to install Ali plug-in to troubleshoot old code and use "==" , Replace with equals

Guess you like

Origin blog.csdn.net/weixin_45496190/article/details/108052884