Sub topic 4
Comparing String Contents
When you compare two pieces of text, you usually want to know whether they contain the same characters. In Java, String provides methods for comparing text by content.
A method is an action you can call on a value. For example, "cat".equals("cat") calls the equals method.
Compare text with `equals`
The equals method checks whether two strings contain the same sequence of text values. It returns a boolean, which is either true or false.
| Comparison | Result | Reason |
|---|---|---|
| `"cat".equals("cat")` | `true` | The text is the same. |
| `"cat".equals("Cat")` | `false` | The first letters have different case. |
| `"cat".equals("cat ")` | `false` | The second string has an extra space. |
| `"".equals("")` | `true` | Both strings are empty. |
An empty string is a string with no text. Its length is zero. A space is text, so " " is not an empty string.
You can use the result in an if statement:
class CheckAnswer {
public static void main(String[] args) {
String answer = "yes";
if (answer.equals("yes")) {
System.out.println("You answered yes.");
} else {
System.out.println("You gave a different answer.");
}
}
}Save this as CheckAnswer.java, then run:
javac CheckAnswer.java
java CheckAnswerThe program prints You answered yes. If you change answer to "Yes", the program prints the other message. The equals method treats uppercase and lowercase letters as different.
Why `==` is different
A String is an object, which is a value created from a class. A string variable holds a reference, which identifies the object it refers to.
For string references, == asks whether both sides refer to the same object. It does not ask whether two separate objects contain the same text.
Try this program:
class CompareStrings {
public static void main(String[] args) {
String first = new String("cat");
String second = new String("cat");
System.out.println(first == second);
System.out.println(first.equals(second));
}
}Save it as CompareStrings.java, compile it, and run it:
javac CompareStrings.java
java CompareStringsThe first line prints false: first and second refer to separate objects. The second line prints true: those objects contain the same text.
This example uses new String(...) to create separate objects for the comparison. You do not need to create strings this way just to compare them.
Compare without regard to case
Use equalsIgnoreCase when uppercase and lowercase differences should not matter:
| Comparison | Result |
|---|---|
| `"yes".equalsIgnoreCase("YES")` | `true` |
| `"yes".equalsIgnoreCase("Yes")` | `true` |
| `"yes".equalsIgnoreCase("no")` | `false` |
For example, you could change the condition in the first program to:
class CheckAnswerIgnoringCase {
public static void main(String[] args) {
String answer = "Yes";
if (answer.equalsIgnoreCase("yes")) {
System.out.println("You answered yes.");
} else {
System.out.println("You gave a different answer.");
}
}
}Now Yes, YES, and yes all produce the first message.
Use this method only when ignoring case fits the task. For example, a password check should follow the rules of the password system; it should not ignore case just for convenience.
Also, equalsIgnoreCase does not follow the special case rules of every language. Text from different languages can need more careful handling than this method provides.
Handle `null` safely
null means a variable does not refer to an object. It is different from "", which refers to an empty string.
You cannot call a method on a null reference. If answer is null, calling answer.equals("yes") causes a NullPointerException. An exception is a signal that something went wrong while the program was running.
When comparing with a known string, put that string before the dot:
class CheckNullableAnswer {
public static void main(String[] args) {
String answer = null;
if ("yes".equals(answer)) {
System.out.println("You answered yes.");
} else {
System.out.println("The answer is not yes.");
}
}
}This prints The answer is not yes. The method is called on "yes", which is not null. Passing null to equals is safe; the result is false.
When either value could be null
The Objects.equals method can compare two values even if either one is null. Add import java.util.Objects; near the top of the file to use the short name Objects.
import java.util.Objects;
class CompareNullableStrings {
public static void main(String[] args) {
String first = null;
String second = "";
String third = null;
System.out.println(Objects.equals(first, second));
System.out.println(Objects.equals(first, third));
System.out.println(Objects.equals("cat", "cat"));
}
}Save, compile, and run this as CompareNullableStrings.java. It prints false, true, and true, in that order.
nulland an empty string are different.- Two
nullvalues compare as equal withObjects.equals. - Two non-null strings are compared by their contents.
Compare strings in order
Sometimes you need to know which string comes before another, rather than just whether they match. Use compareTo for this.
compareTo returns an integer, or whole number. Its sign tells you the result:
| Result | Meaning |
|---|---|
| Negative | The first string comes before the second. |
| Zero | The strings have the same contents. |
| Positive | The first string comes after the second. |
The result need not be exactly -1 or 1. Check whether it is less than, equal to, or greater than zero.
class OrderStrings {
public static void main(String[] args) {
String first = "apple";
String second = "pear";
int result = first.compareTo(second);
if (result < 0) {
System.out.println(first + " comes first.");
} else if (result > 0) {
System.out.println(second + " comes first.");
} else {
System.out.println("The strings match.");
}
}
}This prints apple comes first. The comparison checks corresponding text values from left to right. If the strings match up to the end of the shorter one, the shorter string comes first. For example, "car" comes before "cart".
This is not always the order you would expect from a dictionary. For example, "Zoo".compareTo("apple") is negative: Java places the uppercase Z before the lowercase a in this comparison. Also, compareTo throws a NullPointerException if its argument is null.
Java also has compareToIgnoreCase. Like equalsIgnoreCase, it ignores case differences without applying every language’s special rules. It can return zero for "cat" and "CAT", even though equals returns false for those strings.
Choose the comparison
| Your question | Use |
|---|---|
| Do two non-null strings have exactly the same contents? | `equals` |
| Do they match when case differences should be ignored? | `equalsIgnoreCase` |
| Do two values match when either might be `null`? | `Objects.equals` |
| Which non-null string comes first in Java’s order? | `compareTo` |
| Do two references point to the same object? | `==` |
Exercise
What do "dog".equals("Dog") and "dog".equalsIgnoreCase("Dog") return?
Show answer
They return false and true, respectively. The first comparison checks case; the second ignores it.
Exercise
If first and second are both null, what does Objects.equals(first, second) return? What happens if you call first.equals(second)?
Show answer
Objects.equals returns true. Calling first.equals(second) throws a NullPointerException because first is null.
Exercise
If a.compareTo(b) returns -4, what can you conclude?
Show answer
a comes before b in Java’s string order. The result is negative, so it does not need to be exactly -1.