DivideByHero DivideByHero - 5 months ago 40
Java Question

Java: Is assertEquals(String, String) reliable?

I know that

has some issues when comparing two
. It seems that
is a better approach. Well, I'm doing JUnit testing and my inclination is to use
assertEquals(str1, str2)
. Is this a reliable way to assert two Strings contain the same content? I would use
, but then you don't get the benefit of seeing what the expected and actual values are on failure.

On a related note, does anyone have a link to a page or thread that plainly explains the problems with
str1 == str2


You should always use .equals() when comparing Strings in Java.

JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).

So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)

Here is a link to a great Stackoverflow question regarding some of the differences between == and .equals().