Java String comparison FAQ: How to compare Java Strings

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 for better or worse, 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 Java String comparison tutorial I'll also discuss why the == operator doesn't work when comparing Java strings.

Option 1: Java String comparison with the equals method

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

if (string1.equals(string2))

This 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.")
}

Option 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.")
}

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

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

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

Thanks a bunch

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

Thanks!

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

This is exactly the kind of

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

I was perplexed for a while,

I was perplexed for a while, great post

re: Option 3: Java String

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

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!

THanks for the help

You have really helped me thank you very much

compareTo

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
}

Thanks for the post. I quick

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

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.

== works

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

Thanks a lot.

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

Example of how/why "==" doesn't work

In response to the "== works" post, I'm afraid the Java compiler is just playing a cruel trick here.

It's a little early in the morning for me and I'm not saying this right, but in an optimization effort, the compiler will take any references it sees to the same String literal, and essentially make those references the same. In C, we would say the pointers all point to the same thing in memory.

Here's a simple case that will make you think "==" works with Java:

public class JavaStringCompareEqual1
{
  public static void main(String[] args)
  {
    // this will print; the compiler is smart
    String s1 = "foobar";
    String s2 = "foobar";
    // this will print
    if (s1 == s2) System.out.println("s1 and s2 are ==");
  }
}

But here we confuse the compiler just enough to make "==" not work:

public class JavaStringCompareEqual2
{
  public static void main(String[] args)
  {
    // this will print; the compiler is smart
    String s1 = "foobar";

    // fool the compiler just a bit
    String s3 = "foo";
    s3 = s3 + "bar";

    if (s1 == s3) 
      System.out.println("s1 and s3 are ==");
    else
      System.out.println("s1 and s3 ARE NOT ==");

    // show that they really are the same
    System.out.format("s1 is '%s'\n", s1);
    System.out.format("s3 is '%s'\n", s3);
  }
}

This second example will print the following:

"s1 and s3 ARE NOT =="

So great post

So great post

Well explained and very

Well explained and very helpful! Thanks.

Thanks a million

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

Fantastic Explanation

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

The real reason why == does not work

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

'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".

operator overloading

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

thanks

thanks man..that was a timely help

The REAL reason "==" doesn't work

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

Post new comment

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