Learn Java · lesson 34 of 61 · about 8 minutes
equals versus ==
Check the customer's voucher code: understand why Strings must be compared with equals, and what == really checks.
What you'll learn
- Explain references
- Compare text with equals
- Compare alphabetically with compareTo
A voucher code
Tonight, customers with the voucher code PIRATES10 get 10% off their bill. The desk reads the code with in.next() and has to decide whether it's the right one. voucher == "PIRATES10" looks right but says false even when the code is typed perfectly, because a String read with Scanner is a new object. voucher.equals("PIRATES10") compares the characters, and equalsIgnoreCase does the same while ignoring capitals, so pirates10 works too.
Variables that point to objects
A String variable doesn't hold the text itself; it holds a reference to a String object somewhere in memory.
a == basks "do a and b point to the very same object?"a.equals(b)asks "do they contain the same characters?"
Two different objects can hold the same text, so == can say false even when the words match. Always use equals for Strings (and for other objects).
Same text, different objects
public class Main {
public static void main(String[] args) {
String a = "cat";
String b = new String("cat");
String c = a;
System.out.println((a == b) + " " + a.equals(b));
System.out.println(a == c);
System.out.println("apple".compareTo("banana") < 0);
}
}Output
false true
true
trueTip
a.compareTo(b) is negative if a comes first alphabetically, 0 if equal, and positive if a comes after. It's what sorting uses.
Ignoring capitals
public class Main {
public static void main(String[] args) {
String typed = "pirates10";
System.out.println(typed.equals("PIRATES10") + " " + typed.equalsIgnoreCase("PIRATES10"));
}
}Output
false trueNow try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.