Compare Strings: equals() and compareTo()
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)To check whether two Strings hold the same text, use equals(). To put them in dictionary order, use compareTo(). Never use == for text.
equals(): the same text?
A quiz app must check whether the typed answer is right. a.equals(b) is true when both Strings have the same characters in the same order; capitals count, unless you use equalsIgnoreCase().
Example 1 · A yes/no answer in any capitals
import java.util.Scanner;
public class YesNo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Continue? (yes/no): "); String ans = sc.nextLine().trim(); if (ans.equalsIgnoreCase("yes")) { System.out.println("Continuing..."); } else { System.out.println("Stopped."); } sc.close(); }}Continue? (yes/no): YES Continuing...
What this code does
- The sample shows the user typing
YES. WithequalsIgnoreCase(),yes,YesandYESall work. trim()removes outer spaces first (Change case, trim and replace (opens in a new tab)), so" yes "works too.
Experiment
Compare lab
Type two words. Try Yes and yes, then yes and yes with a space.
- a.equals(b)
- false
- a.equalsIgnoreCase(b)
- true
Why == is wrong for text
Two Strings both print Ravi, yet == says false. A String variable holds the address of its object, like an array variable (opens in a new tab), so == asks "the same object?", not "the same text?".
Example 2 · Same text, but == says false
public class CompareNames { public static void main(String[] args) { String a = "Ravi"; String part = "Ra"; String b = part + "vi"; System.out.println(a + " and " + b); System.out.println("a == b: " + (a == b)); System.out.println("a.equals(b): " + a.equals(b)); }}Ravi and Ravi a == b: false a.equals(b): true
What this code does
bis built while the program runs, so it is a new object that happens to hold the same text.a == bcompares the two objects and givesfalse;a.equals(b)compares the characters and givestrue.- The brackets in
(a == b)matter: without them,+would join the text first.
Java keeps one shared copy of each literal such as "Ravi" in the String pool, so two literals can give == as true by luck. Text from Scanner, from + with a variable or from a method is a new object, and then == fails.
equals(). Use == only for numbers, char and boolean.compareTo(): dictionary order
A class list must print names in alphabetical order. a.compareTo(b) gives a negative number when a comes first, 0 when the texts are equal, and a positive number when a comes after b.
Example 3 · Which name comes first?
public class NameOrder { public static void main(String[] args) { System.out.println("Amit".compareTo("Bala")); System.out.println("Bala".compareTo("Amit")); System.out.println("Amit".compareTo("Amit")); String x = "Neha"; String y = "Karan"; if (x.compareTo(y) < 0) { System.out.println(x + " comes first"); } else { System.out.println(y + " comes first"); } }}-1 1 0 Karan comes first
What this code does
Acomes beforeB, so"Amit".compareTo("Bala")is negative; swapping them makes it positive, and equal texts give 0."Neha".compareTo("Karan")is positive, becauseNcomes afterK, so theelsepart printsKaran comes first.
Only the sign matters, so test < 0 or > 0, never == -1. Java compares character codes, so every capital letter comes before every small letter: "Zara" comes before "anu". compareToIgnoreCase() ignores capitals.
Next step
Check your understanding
9 quick questions