Use the equals() method to check whether two strings contain the same text. Use equalsIgnoreCase() when capitalization should not affect the comparison.
In this example, you will compare strings with identical text and strings with different capitalization.
Source code
Save the following code as StringComparisonExample.java:
public class StringComparisonExample {
void main() {
String first = "Java";
String second = new String("Java");
String third = "java";
IO.println("Same text: " + first.equals(second));
IO.println("Same object: " + (first == second));
IO.println("Same case-sensitive text: " + first.equals(third));
IO.println("Same text ignoring case: "
+ first.equalsIgnoreCase(third));
}
}
Explanation
The example creates three string variables:
String first = "Java";
String second = new String("Java");
String third = "java";
The first two strings contain identical text. The third starts with a lowercase letter.
The explicit new String("Java") creates a separate object to demonstrate the difference between comparing text and comparing references. In ordinary code, prefer a string literal when you do not need a separate object.
Comparing text with equals()
The equals() method compares the contents of strings:
first.equals(second)
This returns true because both strings contain "Java".
The comparison is case-sensitive:
first.equals(third)
This returns false because "Java" and "java" have different capitalization.
Comparing references with ==
For strings, the == operator checks whether two references point to the same object:
first == second
This returns false because second refers to a separately created string object, even though the text is identical.
String literals may share an object, so == can sometimes return true for strings containing the same text. Always use equals() when your intention is to compare their contents.
Ignoring capitalization
Use equalsIgnoreCase() when letter case should not affect the result:
first.equalsIgnoreCase(third)
This returns true for "Java" and "java".
Run the example
Compile and run the file:
javac StringComparisonExample.java
java StringComparisonExample
Output
Same text: true
Same object: false
Same case-sensitive text: false
Same text ignoring case: true
Handling null values
Calling equals() on a variable containing null throws a NullPointerException.
When comparing a variable with a known string literal, put the literal first:
"Java".equals(value)
This returns false if value is null.
If either of two variables may be null, use Objects.equals():
Objects.equals(firstValue, secondValue)
Import java.util.Objects to use this method. It returns true when both arguments are null, and otherwise compares their values safely.
