Java substring.equals vs ==

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

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

and he broke the iteration. After the first increment, no additional instances of the "dog" will be detected.

So, I used substring.equals and this worked:

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

My question is why? Just looking for a better understanding, thanks.

+4
source share
5 answers

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

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

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

+8
source

== compares links. Instead, you want to compare values ​​using equals() .

+8
source

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

and

.equals() compares the value of strings

+4
source

To compare String always use the equals() method. Because comparing with == compares links.

Here is a link for more knowledge.

You can also read this to better understand the difference between == and equals() methods and code examples.

+4
source

"String" is an object in Java, so "==" compares the links as indicated. However type code

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

actually prints "Equal!", which may confuse you. The reason is that the JVM optimizes your code a bit when directly assigning literals to String objects, so str1 and str2 actually refer to the same object that is stored in the internal pool inside the JVM. Code, on the other hand

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

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

+3
source

Source: https://habr.com/ru/post/1414433/


All Articles