Home>Article>Java> Java development == and equals()

Java development == and equals()

无忌哥哥
无忌哥哥 Original
2018-07-23 09:48:46 1979browse

The

== sign compares values when comparing basic data types, but when using the == sign to compare two objects, it compares the address values of the two objects.

equals() In the case of overriding, the memory address is compared, but most classes in Java have overridden the equals() method, so the values are compared

String str1 = "abc"; String str2 = "abc"; System.out.println(str1.equals(str2)); System.out.println(str1 == str2);

In this case, true and true are returned, and the second = = also returns true:

Because the constant pool in the memory belongs to the method area. When str1 is created, there is no constant pool, so the object "abc" is created in the constant pool. When str2 is created, the constant It already exists in the pool, so it will be used directly when creating it for the second time, so the address is the same

If it is changed to

String str1 = new String("abc"); String str2 = new String("abc");

str1==str2, it will return false because two objects are created. , the address is different.

The above is the detailed content of Java development == and equals(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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