The difference and usage of equals() and == in Java
In Java development, there is a seemingly simple topic, but there are a lot of topics and questions on the Internet, which is what is the difference between equals() and the == operator
- ==: The operator is used to compare whether the addresses of two objects are equal.
- equals(): The method is used to compare whether the contents of two objects are equal.
Today Content introduction, takes about 9 minutes
Picture
To better understand the difference, let’s look at an example:
String str1 = new String("Hello");String str2 = new String("Hello");System.out.println(str1.equals(str2)); // 输出 trueSystem.out.println(str1 == str2); // 输出 false
In the example, although the contents of the two strings are the same, their addresses in memory are different. Therefore, using the .equals() method to compare their contents will return true, while using the "==" operator to compare their addresses will return false
1. Overriding the .equals() method
Those who have studied the basics of Java should know that all Java classes inherit the Object class by default. There is an .equals() method in the Object class
public boolean equals(Object obj) {return (this == obj);}
You can find .equals( from the code ) method uses the == operator for comparison by default. If the subclass does not override the equals() method, then use the == operator and the equals() method. The result is exactly the same - used to compare whether the memory addresses of two objects are equal.
But the actual situation is that many classes override the equals() method. This is because the memory address comparison requirements are strict and do not meet the needs of all real-life scenarios. For example, the String class, when comparing, most I just want to determine whether the contents are equal, and I don't really want to know whether the memory address is equal (whether it is an object).
In the article on in-depth study of the Java string constant pool, we have learned that the Java virtual machine allocates a separate space for strings in order to optimize memory utilization and improve performance - the string constant pool.
It is recommended to use String s = "Hello" to create a string object instead of using the new keyword, because new requires additional allocation of memory space on the heap.
1.1. The equals() method of the String class
The equals() method of the String class of Jdk11
public boolean equals(Object anObject) { //如果是同一个对象(即两个引用指向内存中的同一块地址),则直接返回trueif (this == anObject) {return true;} //如果是String类型的实例if (anObject instanceof String) { //Object类型的对象强制转换为String类型String aString = (String)anObject;//如果当前字符串对象和传入的字符串对象的编码方式相同if (coder() == aString.coder()) { //如果当前字符串和传入的字符串都是Latin1编码,则调用StringLatin1类的equals方法进行比较;如果其中一个或两个字符串是UTF16编码,则调用StringUTF16类的equals方法进行比较return isLatin1() ? StringLatin1.equals(value, aString.value): StringUTF16.equals(value, aString.value);}}return false;}
Special note: Latin1 (also known as (ISO 8859-1) and UTF-16 (Unicode conversion format 16-bit) are two different character encoding methods
Although Latin1 and UTF-16 are two encoding methods, the difference is not big, just take Look at the equals() method from UTF-16
@HotSpotIntrinsicCandidatepublic static boolean equals(byte[] value, byte[] other) {if (value.length == other.length) {int len = value.length >> 1;for (int i = 0; i
Note: The source code of the equals() method of Java8 and Java11 is different. The equals() method of JDK8
public boolean equals(Object anObject) {// 如果是同一个对象(即两个引用指向内存中的同一块地址),则直接返回trueif (this == anObject) {return true;}// 如果是String类型的实例if (anObject instanceof String) {////Object类型的对象强制转换为String类型String anotherString = (String)anObject;int n = value.length;// 如果字符串长度相等if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;// 判断每个字符是否相等while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}
1.2. Example explanation
Example 1:
new String("hello").equals("hello")
What is the output result?
equals of String class The method compares whether the contents of the string objects are equal. Because they are all "Hello", the result is true
Example 2:
new String("hello") == "hello";
What is the output result?
== Whether the object addresses compared by the operator are equal, == The left side is the object created in the heap, and the right side is the string constant pool object. Although the contents are equal, the addresses are not equal, so the result is false
Example 3:
new String("hello") == new String("hello");
What is the output result?
The object coming out of new must be a completely different memory address, so the result is false
Example 4:
"hello" == "h"+"ello"
What is the output result?
h and ello are both in the string constant pool, so the compiler will It is automatically optimized to hello, so the result is true
Example 5:
new String("hello").intern() == "hello"
What is the output result?
new String("hello") During execution, the object will be created first in the string constant pool, and then in the heap; when executing the intern() method, it is found that the object 'hello' already exists in the string constant pool, so it returns directly The object in the string constant pool is referenced, and then compared with 'hello' in the string constant pool, so the result is true
In-depth analysis of String.intern() has already introduced the reasons
2. Other comparison methods
In addition to the .equals() method and the "==" operator, there are some other comparison methods that can be used:
- 1.Objects.equals() method: This static method can be used to compare whether two objects are equal. There is no need to determine whether the object is empty before calling.
Objects.equals("Hello", new String("Hello")); // 返回 true
- 2. The .contentEquals() method of the String class: This method can be used to compare a string with any character sequence (such as StringBuffer, StringBuilder, String, CharSequence) are equal.
String str = "Hello";StringBuffer buffer = new StringBuffer("Hello");System.out.println(str.contentEquals(buffer)); // 输出 true
The above is the detailed content of The difference and usage of equals() and == in Java. For more information, please follow other related articles on the PHP Chinese website!

This article explores the growing concern of "AI agency decay"—the gradual decline in our ability to think and decide independently. This is especially crucial for business leaders navigating the increasingly automated world while retainin

Ever wondered how AI agents like Siri and Alexa work? These intelligent systems are becoming more important in our daily lives. This article introduces the ReAct pattern, a method that enhances AI agents by combining reasoning an

"I think AI tools are changing the learning opportunities for college students. We believe in developing students in core courses, but more and more people also want to get a perspective of computational and statistical thinking," said University of Chicago President Paul Alivisatos in an interview with Deloitte Nitin Mittal at the Davos Forum in January. He believes that people will have to become creators and co-creators of AI, which means that learning and other aspects need to adapt to some major changes. Digital intelligence and critical thinking Professor Alexa Joubin of George Washington University described artificial intelligence as a “heuristic tool” in the humanities and explores how it changes

LangChain is a powerful toolkit for building sophisticated AI applications. Its agent architecture is particularly noteworthy, allowing developers to create intelligent systems capable of independent reasoning, decision-making, and action. This expl

Radial Basis Function Neural Networks (RBFNNs): A Comprehensive Guide Radial Basis Function Neural Networks (RBFNNs) are a powerful type of neural network architecture that leverages radial basis functions for activation. Their unique structure make

Brain-computer interfaces (BCIs) directly link the brain to external devices, translating brain impulses into actions without physical movement. This technology utilizes implanted sensors to capture brain signals, converting them into digital comman

This "Leading with Data" episode features Ines Montani, co-founder and CEO of Explosion AI, and co-developer of spaCy and Prodigy. Ines offers expert insights into the evolution of these tools, Explosion's unique business model, and the tr

This article explores Retrieval Augmented Generation (RAG) systems and how AI agents can enhance their capabilities. Traditional RAG systems, while useful for leveraging custom enterprise data, suffer from limitations such as a lack of real-time dat


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool