Home > Java > Javagetting Started > The difference between java equals and ==

The difference between java equals and ==

(*-*)浩
Release: 2019-11-15 09:22:58
Original
9113 people have browsed it

The difference between java equals and ==

java9 example code: (Recommended learning: java course)

String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
String str4 = new String("abc");
Copy after login
当:  str1 == str2    输出:true    当:str1.equals(str2); 输出:true
当:  str1 == str3 输出:false      当:str1.equals(str3); 输出:true
当:  str3 == str4 输出:false      当:str3.equals(str4); 输出:true
Copy after login

Details involved:

- You can use the intern method in String. The string object has a reference to the string that is equal to it in the constant pool.

str3.intern() == str4.intern()  输出:true
str1.intern().equals(str2.intern())  输出:true
str1.intern() == str1   输出:false
- String str = new String("abc");创建了几个对象?
Copy after login

First of all, check whether there is "abc" in the constant pool. This string, if it exists (String str = "abc"; when it appears), creates one, if not, creates two (one in the constant pool, one in the heap).

The difference between equals and ==

For ==:

Acts on variables of basic data types , then directly compare whether the stored "values" are equal;

acts on reference type variables, then the comparison is the address of the object pointed to;

For equals:

The equals method cannot be applied to variables of basic data types;

If there is no equals method in Object If rewritten, the comparison is the address of the object pointed to by the reference type variable, otherwise the content is compared

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

Related labels:
source:php.cn
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