← Back to Chapters

Java String Comparison

? Java String Comparison

? Quick Overview

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.

? Key Concepts

  • == compares object references
  • equals() compares string values
  • equalsIgnoreCase() ignores case sensitivity
  • compareTo() compares lexicographically

? Syntax / Theory

Java provides multiple ways to compare strings depending on whether you want to compare memory references or actual content.

? Code Example(s)

? View Code Example
// 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"));

}
}

? Live Output / Explanation

true → same string literal reference

false → different object reference

true → same string content

true → case ignored

-1 → lexicographical difference

? Interactive Simulator

Type two values and click a method to see the result:

> Click a button to compare...

✅ Tips & Best Practices

  • Always use equals() for content comparison
  • Avoid using == unless checking show same reference
  • Use equalsIgnoreCase() for user input
  • compareTo() is useful for sorting

? Try It Yourself

  • Compare two user-input strings
  • Sort an array of strings using compareTo()
  • Test case-sensitive vs case-insensitive comparison