0
0
Javaprogramming~15 mins

String comparison in Java

Choose your learning style8 modes available
menu_bookIntroduction
We compare strings to check if two pieces of text are the same or to find their order.
Checking if a user entered the correct password.
Sorting a list of names alphabetically.
Finding if two words are equal in a game.
Comparing input commands in a program.
regular_expressionSyntax
Java
string1.equals(string2)
string1.equalsIgnoreCase(string2)
string1.compareTo(string2)
Use equals() to check if two strings have exactly the same characters.
Use equalsIgnoreCase() to compare strings ignoring uppercase or lowercase differences.
Use compareTo() to find the alphabetical order between two strings.
emoji_objectsExamples
line_end_arrow_notchChecks if both strings are exactly the same.
Java
String a = "hello";
String b = "hello";
boolean result = a.equals(b);
line_end_arrow_notchChecks if strings are the same ignoring case differences.
Java
String a = "Hello";
String b = "hello";
boolean result = a.equalsIgnoreCase(b);
line_end_arrow_notchReturns a negative number because "apple" comes before "banana" alphabetically.
Java
String a = "apple";
String b = "banana";
int result = a.compareTo(b);
code_blocksSample Program
This program compares two strings using three methods and prints the results.
Java
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));
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch
The equals() method is case sensitive.
line_end_arrow_notch
The 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.
line_end_arrow_notch
Always use equals() or equalsIgnoreCase() to compare string content, not the == operator.
list_alt_checkSummary
Use equals() to check if two strings are exactly the same.
Use equalsIgnoreCase() to ignore letter case when comparing.
Use compareTo() to find alphabetical order between strings.