What is the difference between equals and == when comparing Strings in Java?
The two of them ask completely different questions, and only one of them is about the text.
The operator == asks whether the two variables point at the same object in memory. The method equals asks whether the two strings hold the same text.
public class Main {
public static void main(String[] args) {
String a = new String("tutorsbot");
String b = new String("tutorsbot");
// Two different objects with the same text.
System.out.println("a == b : " + (a == b));
System.out.println("a.equals(b): " + a.equals(b));
// Two literals are shared, so this one happens to be true.
String first = "hello";
String second = "hello";
System.out.println("literal == literal : " + (first == second));
System.out.println("literal equals : " + first.equals(second));
}
}
Look at the first pair of lines. The two strings were built with the new keyword, so they are two separate objects, and the == comparison is false even though the text is identical. The equals comparison is true, because it looks at the text.
Now look at the second pair. The two literals are the same object, because the compiler puts text that you write in your code into a shared place, so the == comparison is true as well. That is why == appears to work for a long time. It works until you build one of the strings while the program is running, and then it suddenly stops working.
So the rule is simple. When you are comparing text, use equals, and never ==.
The next question in this topic looks at the one case where == is defensible.