Introduction
We compare strings to check if two pieces of text are the same or to find their order.
string1.equals(string2) string1.equalsIgnoreCase(string2) string1.compareTo(string2)
equals() to check if two strings have exactly the same characters.equalsIgnoreCase() to compare strings ignoring uppercase or lowercase differences.compareTo() to find the alphabetical order between two strings.String a = "hello"; String b = "hello"; boolean result = a.equals(b);
String a = "Hello"; String b = "hello"; boolean result = a.equalsIgnoreCase(b);
String a = "apple"; String b = "banana"; int result = a.compareTo(b);
public class Main { public static void main(String[] args) { String word1 = "Java"; String word2 = "java"; System.out.println("Using equals: " + word1.equals(word2)); System.out.println("Using equalsIgnoreCase: " + word1.equalsIgnoreCase(word2)); System.out.println("Using compareTo: " + word1.compareTo(word2)); } }
equals() method is case sensitive.compareTo() method returns 0 if strings are equal, a negative number if the first string is alphabetically before the second, and a positive number if after.equals() or equalsIgnoreCase() to compare string content, not the == operator.equals() to check if two strings are exactly the same.equalsIgnoreCase() to ignore letter case when comparing.compareTo() to find alphabetical order between strings.String s1 = "Hello";String s2 = "hello";== compares references, not content, so it is not reliable for string content comparison.equals() checks if two strings have exactly the same characters and case, which is what is asked.s1 and s2 ignoring case in Java?equalsIgnoreCase() to compare strings ignoring letter case differences.s1.equalsIgnoreCase(s2) is the correct method call syntax.String a = "apple";
String b = "banana";
int result = a.compareTo(b);
System.out.println(result > 0 ? "a > b" : "a <= b");
compareTo() returns a negative number if the first string is alphabetically before the second.a.compareTo(b) returns a negative value, making result > 0 false.String s1 = "Java";
String s2 = "java";
if (s1 == s2) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
== compares if both variables point to the same object, not if their text is equal.s1.equalsIgnoreCase(s2) to compare string content ignoring case.s1 and s2 for sorting?compareToIgnoreCase() compares strings alphabetically ignoring case and returns an int for sorting.String class has compareToIgnoreCase() for this purpose.Pass the test and this pattern moves unknown