Java 25 (LTS) reference · String Methods
Java String equals() Method
Compare the contents of two strings. Never use == for strings: it compares object identity, not text.
Java 25 (LTS) Since Java 1.0
Syntax
string.equals(other)
Parameters
| Parameter | Description |
|---|---|
otherObject |
The object to compare with. |
Return value
true if the text is the same.
Examples
public class Main {
public static void main(String[] args) {
String a = "java";
String b = new String("java");
System.out.println(a == b); // different objects
System.out.println(a.equals(b)); // same text
System.out.println(a.equalsIgnoreCase("JAVA"));
}
}
Output
false true true
Run this on your computer — see “Get Started” for setup.
public class Main {
public static void main(String[] args) {
String input = null;
System.out.println("yes".equals(input)); // safe: no NullPointerException
System.out.println(java.util.Objects.equals(input, null));
}
}
Output
false true
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.compareTo()· Compare two strings alphabetically: negative if this comes first, 0 if equal, positive if it comes after.string.toUpperCase()· Return a copy of the string in upper case. toLowerCase() does the opposite.- Java Strings · tutorial