Table of Contents
1. Overriding the .equals() method
1.1. The equals() method of the String class
1.2. Example explanation
2. Other comparison methods
Home Technology peripherals AI The difference and usage of equals() and == in Java

The difference and usage of equals() and == in Java

Mar 07, 2024 pm 03:28 PM
java object string class String constant true

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

The difference and usage of equals() and == in JavaPicture

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

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);}
Copy after login

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;}
Copy after login

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

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;}
Copy after login

1.2. Example explanation

Example 1:

new String("hello").equals("hello")
Copy after login

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";
Copy after login

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");
Copy after login

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

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

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

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!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles