String comparison in Java is used to check whether two strings are equal, which string comes first lexicographically, or whether two string objects refer to the same memory location.
== compares object referencesequals() compares string valuesequalsIgnoreCase() ignores case sensitivitycompareTo() compares lexicographicallyJava provides multiple ways to compare strings depending on whether you want to compare memory references or actual content.
// Demonstrating different string comparison methods in Java
public class StringComparison {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
System.out.println(s1.equalsIgnoreCase("java"));
System.out.println(s1.compareTo("Javb"));
}
}
true → same string literal reference
false → different object reference
true → same string content
true → case ignored
-1 → lexicographical difference
Type two values and click a method to see the result:
equals() for content comparison== unless checking show same referenceequalsIgnoreCase() for user inputcompareTo() is useful for sortingcompareTo()