Home > Java > Javagetting Started > body text

Comparative operation analysis of == and equals in java

王林
Release: 2020-11-17 15:11:33
forward
2362 people have browsed it

Comparative operation analysis of == and equals in java

Comparative analysis:

(Learning video sharing: java course)

==: Its function is to judge the two Are the addresses of the two objects equal? That is: determine whether two objects are the same object. (Basic data types compare values, and reference data types == compare memory addresses).

equals(): Its function is also to determine whether two objects are equal. But it generally has two usage cases, as follows:

Case 1: The class does not cover the equals() method. Then comparing two objects of this class through equals() is equivalent to comparing the two objects through ==.

Case 2: The class overrides the equals() method. Generally, we override the equals() method to ensure that the contents of the two objects are equal; if their contents are equal, true is returned (that is, the two objects are considered equal).

Code example:

public class test1 {
	public static void main(String[] args) {
		String a = new String("ab"); // a 为一个引用
		String b = new String("ab"); // b 为另一个引用,对象的内容一样
		String aa = "ab"; // 放在常量池中
		String bb = "ab"; // 从常量池中查找
		if (aa == bb) // true
		System.out.println("aa==bb");
		if (a == b) // false,非同一对象
		System.out.println("a==b");
		if (a.equals(b)) // true
		System.out.println("aEQb");
		if (42 == 42.0) // true
		System.out.println("true");
	}
}
Copy after login

The equals method in String has been overridden, because the equals method of object compares the memory address of the object, while the equals method of String compares the object. value. When creating an object of type String, the virtual machine searches the constant pool to see if there is an existing object with the same value as the one to be created, and if so, assigns it to the current reference. If not, re-create a String object in the constant pool.

Related recommendations:Getting started with java

The above is the detailed content of Comparative operation analysis of == and equals in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template