How to compare String equality in Java

Java String comparison FAQ: Can you share some examples of how to compare strings in Java?

If you’re like me, when I first started using Java, I wanted to use the == operator to test whether two String instances were equal, but that's not the correct way to do it in Java.

In this tutorial I’ll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. At the end of this tutorial I’ll also discuss why the == operator doesn’t work when comparing Java strings.

Back to top

1) Solution 1: Java String comparison with the 'equals' method

Most of the time — maybe 95% of the time — I compare Java strings with the equals method of the String class, like this:

if (string1.equals(string2))

The String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal.

Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different):

String string1 = "foo";
String string2 = "FOO";

if (string1.equals(string2))
{
  // this line will not print because the
  // java string equals method returns false:
  System.out.println("The two strings are the same.")
}

But, when the two strings contain the exact same string of characters, the equals method will return true, as in this example:

String string1 = "foo";
String string2 = "foo";

// test for equality with the java string equals method
if (string1.equals(string2))
{
  // this line WILL print
  System.out.println("The two strings are the same.")
}
Back to top

2) Solution 2: String comparison with the 'equalsIgnoreCase' method

In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:

String string1 = "foo";
String string2 = "FOO";

// java string compare while ignoring case
if (string1.equalsIgnoreCase(string2))
{
  // this line WILL print
  System.out.println("Ignoring case, the two strings are the same.")
}
Back to top

3) Solution 3: Java String comparison with the 'compareTo' method

There is also a third, less common way to compare Java strings, and that's with the String class compareTo method. If the two strings are exactly the same, the compareTo method will return a value of 0 (zero). Here's a quick example of what this string comparison approach looks like:

String string1 = "foo bar";
String string2 = "foo bar";

// java string compare example
if (string1.compareTo(string2) == 0)
{
  // this line WILL print
  System.out.println("The two strings are the same.")
}

(As a quick note, I haven't used this approach in many years. If anyone would like to add a comment on when this approach is recommended, please leave a note below.)

Back to top

4) Java String compare:  why “==” doesn’t work

As I mentioned above, when I first began working with Java I wanted to compare strings with the == operator, like this:

if (string1 == string2)
{
  // do something ...
}

However, unlike C++, Java does not let us overload operators like the == operator. The designers of the Java language intentionally made this design decision to simplify the language. While it seems counter-intuitive at first, once you realize that there is an equals method on the String class, it’s not a big deal.

(For more information on == in regards to Java String comparison, please see a detailed explanation in the comments area below, specifically the comment entry title “Example of how/why ‘==’ doesn't work”.)

Back to top

5) A closing note - the Java Object equals method

While I’m writing about this concept of equality in Java, it’s important to note that the Java language includes an equals method in the base Java Object class. Whenever you’re creating your own objects and you want to provide a means to see if two instances of your object are “equal,” you should override (and implement) this equals method in your class (in the same way the Java language provides this equality/comparison behavior in the String equals method).

Back to top
Permalink

Thank you both the information about the "right" way and the "wrong" way were very helpful.

Permalink

Thank you so much!! This helped me tons and saved me hours of frustration!

Permalink

This is exactly the kind of information that makes me love the internet just a little bit more every day.

Permalink

re: Option 3: Java String comparison with the compareTo method

-1 or 1 is returned if string1 > string 2 and vice-versa. If they are the same, zero is returned.

Thanks for the note regarding Option #3. Showing the -1 or +1 result is probably a more useful example of the compareTo method than what I showed above, as it shows how to perform a quick sorting comparison. Thanks again!

Use the compareTo method, if you are interested in the lexicographic order of the strings - which is "less", which is "greater". If you want to sort the strings, or quickly looking in a sorted array of strings, you need all 3 possible return values - less, equal or greater -, so store the result of the compareTo() in an integer variable:

int result = str1.compareTo(str2);
if (result == 0) {
// strings are equal
} else if (result < 0) {
// str1 is before str2
}

Permalink

Thanks for the post. I quick doubt.

What if i need to compare a emtpry string with my vairable. Would String1.equals(""); work ??? because in the documentation of equals i found eqyals

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

?????

Yes, that will work. Usually what I do is add the trim() method to the String first, just in case the String contains all blank spaces, like this:

if (myString.trim().equals("")) 
{
  // do something
}

But really, that depends on the application, and whether you think "" and " " should be evaluated the same way.
Also, while I'm in the neighborhood, I didn't mention it in the article, but if you need to check for a null String, that test looks like this:

if (myString == null)
{
  // do something
}

This should probably be the first test in a custom compareTo method.

Permalink

I wanted to see the functionality and string1 == "value of string1" also returns true just like string1.equals("value of string1") returns true...

Permalink

I got answer of my interview question.
Thanks a lot for clearing my idea.

Permalink

You just saved my day. I was trying the "==" in a code and it didnt work. Thanks again

Permalink

I had been looking everywhere to find why == would work sometimes when I thought it shouldn't. Great explanation, thanks so much!

Permalink

Isn't it possible to include your November 29, 2009 - 3:47pm explanation of why == does not work in the main article ? I've had to parse all comments to find this all-important piece of information (I'm a Java newbie otherwise I would/should have known, of course...)

As of "not a big deal" -- Personally I'm somewhat annoyed that == does not work. Because ".equals(" obfuscates the code to my eyes: what happens is less obvious, perhaps only slightly so but there are times where that counts (e.g. when you quickly reread code, or when you have many parenthesis and equals() adds more).

The second reason is that my co-workers imported the ".equals(" idiom to C# where it is not needed (thanks Bill, for once). But thanks to you I know why .equals appears in Java (will keep it) and why .equals appears in C# (will replace by == on will).

'However, unlike C++, Java does not let us overload operators like the "==" operator. The designers of the Java language intentionally made this design decision to simplify the Java language. '

I take issue with their definition of "Simplify".

Permalink

"However, unlike C++, Java does not let us overload operators like the "==" operator. The designers of the Java language intentionally made this design decision to simplify the Java language."

I don't think this is correct. Java does not allow *users* to overload operators. A programmer cannot define new methods for applying ">" or "==" to non-numeric objects. However, the Java language does overload its own operators. For example, the "+" operator may be used either for adding integers or concatenating strings. Why the language designers chose not to overload "==" the way they did "+" remains a mystery (to me, anyway).

Permalink

thanks man..that was a timely help

Permalink

Because in java you are comparing references (addresses in memory), NOT the actual characters of text.

Ex:
String x = "Guy" located at memory address 123
String y = "Guy" located at memory address 789

when you compare (x == y) you are actually comparing (123==789) -- hence they are NOT equal

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.