Home Java javaTutorial A brief discussion of equals and == in Java

A brief discussion of equals and == in Java

Dec 16, 2016 am 09:18 AM
equals

When you first learn Java, you may often encounter the following code:

String str1 = new String("hello");
String str2 = new String("hello");
        
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
Copy after login

Why are the output results of lines 4 and 5 different? What is the difference between == and equals methods? If you don't figure this out when you first learn Java, you will make some low-level errors when writing code in the future. Today let’s learn about the difference between == and equals methods.

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

 The following sentence is an original quote from the book "Java Programming Thoughts":

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

This sentence seems simple, but it still needs to be understood carefully. To put it simply, == is used to compare whether values ​​are equal. Let’s take a look at a few examples:

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 after login

The output result is true false true

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

  There are 8 basic data types in Java:

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

Integer type: byte (1 byte), short (2 byte), int (4 byte) , long(8 byte)

 Character type: char(2 byte)

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

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

 That is to say, for example:

 int n= 3;

 int m=3;

  Both variable n and variable m directly store the value "3", so when compared with ==, the result is true.

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

 String str1;

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

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

 str1= new String("hello");

Then str1 points to an object (str1 is also called 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, that is to say, it is not The string "hello" is stored directly. The references here are very similar to pointers in C/C++.

 So when you use == to compare str1 and str2 for the first time, the result is false. Therefore, they point to different objects respectively, which means that the memory addresses where they are actually stored are different.

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 to?

 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, let's look directly at the implementation of the equals method in the Object class.

 The source code path of this class is: Object.java under the java.lang path of src.zip in C:Program FilesJavajdk1.6.0_14 (depending on the personal jdk installation path).

The following is the implementation of the equals method in the Object class:

A brief discussion of equals and == in Java

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 may have questions again, why is the output result of the following piece of code true?

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 after login

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

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

A brief discussion of equals and == in Java

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

  Some other classes, such as Double, Date, Integer, etc., have overridden the equals method to compare whether the contents stored in the pointed objects are equal.

In summary:

 1) For ==, if it acts on a variable of a basic data type, it will directly compare whether its stored "value" is equal;

  If it acts on a variable of a reference type, it will compare the address of the pointed object

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 reference type variable is compared;

 such as String, Date If a class overrides the equals method, the contents of the pointed objects are compared.




For more articles related to equals and == in Java, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles