Home > Java > javaTutorial > Why Does \'==\' Fail to Compare Strings Correctly in Java?

Why Does \'==\' Fail to Compare Strings Correctly in Java?

Mary-Kate Olsen
Release: 2024-11-28 15:26:10
Original
743 people have browsed it

Why Does

String Comparison with ==

In Java, comparing strings using "==" may return unexpected results. Contrary to expectation, applying "==" to two string variables may result in "false" even if they appear identical.

Consider the following code:

String parts[] = {"231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"};

System.out.println("231" == parts[0]); // False
Copy after login

Explanation:

The "==" operator in Java tests whether two objects refer to the same memory location. In the above example, parts[0] and "231" are two separate objects in memory, even though they both hold the same value ("231"). Hence, "231" == parts[0] evaluates to false.

Solution:

To compare the values of strings in Java, use the equals method. The equals method, inherited from Object, returns true if two strings have the same value.

System.out.println("231".equals(parts[0])); // True
Copy after login

Best Practice:

In Java, always use equals for comparing objects, including strings. This practice ensures that you are comparing the values of the objects, not their memory references.

The above is the detailed content of Why Does '==' Fail to Compare Strings Correctly in Java?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template