How to Compare Strings (Determine Equality) in Java

Most of what you need to know about this is explained in great detail in this post.

The short answer is when you create String objects using the String constructor, you cannot use the == operator to compare those two strings in Java (like you can in C#). You have to use the equals method that is built into the Java framework.

String x = new String("abc");
String y = new String("xyz");
String z = new String("abc");
 
System.out.println(x.equals(y)); // false
System.out.println(x.equals(z)); // true
System.out.println(z.equals(x)); // true
System.out.println(x == z); // false
System.out.println(x == y); // false
System.out.println(x == x); // true

You might have thought that x == z would return true because the String values are identical. But in this case, it is comparing the object reference rather than the actual value of the String (“abc”). So == is asking whether the two String objects are the same ones in memory rather than whether they have the same value.

However, I discovered that Java (this may be a new feature to Java 1.6?) will allow you to do this if you declare the Strings as you would primitives. The following code illustrates this. Notice that the second to last line is true instead of false in this one.

String x = "abc";
String y = "xyz";
String z = "abc";
 
System.out.println(x.equals(y)); // false
System.out.println(x.equals(z)); // true
System.out.println(z.equals(x)); // true
System.out.println(x == z); // false
System.out.println(x == y); // true
System.out.println(x == x); // true

Leave a Reply