Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java substring.equals versus ==

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.

like image 747
Jacob Stevens Avatar asked May 25 '12 18:05

Jacob Stevens


1 Answers

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).

like image 63
Alex Lockwood Avatar answered Oct 03 '22 21:10

Alex Lockwood