Java substring.equals versus ==

13,312

Solution 1

You should use equals() instead of == to compare two strings.

s1 == s2 returns true if both strings point to the same object in memory. This is a common beginners mistake and is usually not what you want.

s1.equals(s2) returns true if both strings are physically equal (i.e. they contain the same characters).

Solution 2

== compares references. You want to compare values using equals() instead.

Solution 3

== compares references(storage location of strings) of strings

and

.equals() compares value of strings

Solution 4

For String comparison, always use equals() method. Because comparing on == compares the references.

Here's the link for further knowledge.

You might also want to read this for understanding difference between == and equals() method in a better way along with code examples.

Solution 5

"String" is an object in Java, so "==" compares the references, as stated. However, code like

String str1 = "dog";
String str2 = "dog";
if(str1==str2)
    System.out.println("Equal!");

will actually print out "Equal!", which might get you confused. The reason is that JVM optimizes your code a little bit when you assign literals directly to String objects, so that str1 and str2 actually reference the same object, which is stored in the internal pool inside JVM. On the other hand, code

String str1 = new String("dog");
String str2 = new String("dog");
if(str1==str2)
    System.out.println("Equal!");

will print out nothing, because you explicitly stated that you want two new objects.
If you want to avoid complications and unexpected errors, simply never use "==" with strings.

Share:
13,312
Jacob Stevens
Author by

Jacob Stevens

Updated on June 17, 2022

Comments

  • Jacob Stevens
    Jacob Stevens almost 2 years

    Using the standard loop, I compared a substring to a string value like this:

    if (str.substring(i, i+3) == "dog" ) dogcount++;
    

    and it broke the iteration. After the first increment, no further instances of "dog" would be detected.

    So I used substring.equals, and that worked:

    if (str.substring(i, i+3).equals("dog")) dogcount++;
    

    My question is, why? Just seeking better understand, thx.