What is the difference between == and equals in Java?

Original URL: What is the difference between == and equals in Java_IT Knives Out Blog-CSDN Blog

Introduction

This article introduces the difference between == and equals in Java.

the difference

The difference is: one is an operator and the other is a method.

==

Compares whether the values ​​of variables are the same.

  • If the object of comparison is a basic data type, compare whether the values ​​are equal;
  • If the comparison is a reference data type, the comparison is whether the memory addresses of the objects are equal.

Because Java only transfers by value, for ==, whether it is comparing basic data types or reference data type variables, the comparisons are all values, but the value stored in the reference type variable is the address of the object. Reference type object variables are actually references, and their values ​​point to the memory address where the object is located.

equals method

Check whether the contents of the comparison objects are the same.

The equals() method exists in the Object class, and the Object class is the parent class of all classes. The equals method is defined in the Object class:

public boolean equals(Object obj) {
    return (this == obj);
}
  1. If the class does not override the equals method
    1. When equals is called, the equals method in Object will be called (the == operator is actually used)
  2. If the class overrides the equals method
    1. When equals is called, the class's own equals method will be called (usually to compare whether the contents of the objects are the same). for example:
      1. String: Compare whether the string contents are the same;
      2. Integer: Compare whether the values ​​of the corresponding basic data type int are the same.

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/133265963
Recommended