Java Reference ยท java.lang
Java String.equals() method
Reference for Java String.equals() and equalsIgnoreCase(): comparing string content, why == fails, null-safe comparison and contentEquals.
String.equals(Object) returns true when the argument is a String with exactly the same characters in the same order. It compares content, which is what you almost always want when comparing text. The == operator, by contrast, compares references and can be false for two strings that look identical.
Related methods compare ignoring case (equalsIgnoreCase) or compare against any CharSequence such as a StringBuilder (contentEquals).
"abc".equals("abc"); // true "abc".equals("ABC"); // false "abc".equalsIgnoreCase("ABC"); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public boolean equals(Object anObject) public boolean equalsIgnoreCase(String anotherString) public boolean contentEquals(CharSequence cs)
| Name | Description |
|---|---|
anObject |
The value to compare with. Any type is accepted; non-strings give false. |
anotherString |
The string to compare ignoring case. May be null (gives false). |
cs |
Any character sequence, such as a StringBuilder. |
Returns: true if the contents match; otherwise false. equals(null) is false.
Throws: NullPointerException only when you call the method on a null reference.
Usage notes
- Never use
==for string content. Literals and constants are pooled so==may seem to work in small tests, then fail on strings from input, concatenation ornew String. - Null-safe patterns: put the known non-null value first (
"yes".equals(answer)), or useObjects.equals(a, b). equalsIgnoreCasecompares by simple case folding per character and is not locale-aware, so it is fine for identifiers and commands but not for linguistic comparison.- Unicode forms. Visually identical text can differ in code points (precomposed versus combining marks). Normalize with
java.text.Normalizerfirst. equals(sb)is false for aStringBuilder, because it is not aString. UsecontentEquals()or calltoString().- Ordering is a different question; see compareTo().
- Hashing. Equal strings have equal
hashCode(), so strings work as map keys. The hash is cached in the string. - Performance. Checks identity first, then length and then the characters; O(n) for equal strings, usually much faster for different ones.
- Switch on strings uses
equals()internally, soswitchis case-sensitive too.