String Comparison
Part of the Fundamentals section of Coddy's Java journey — lesson 21 of 73.
In Java, comparing strings is different from comparing numbers. While you can use <, >, ==, etc., for numbers, strings require different methods because they are objects, not primitive.
The most common and correct way to compare if two strings have the same content is using the equals() method:
String str1 = "hello";
String str2 = "hello";
String str3 = "Hello";
boolean result1 = str1.equals(str2); // true
boolean result2 = str1.equals(str3); // false (case-sensitive)Using equalsIgnoreCase() If you want to compare strings without considering upper/lower case:
String str1 = "Hello";
String str2 = "hello";
boolean result = str1.equalsIgnoreCase(str2); // trueMany beginners try to use == to compare strings, but this is usually wrong:
String str1 = "hello"; String str2 = "hello"; boolean result = (str1 == str2);
Don't comapre string with the
==sign!
Cheat sheet
In Java, strings are objects and require special methods for comparison:
Use equals() to compare string content (case-sensitive):
String str1 = "hello";
String str2 = "hello";
String str3 = "Hello";
boolean result1 = str1.equals(str2); // true
boolean result2 = str1.equals(str3); // falseUse equalsIgnoreCase() to compare strings ignoring case:
String str1 = "Hello";
String str2 = "hello";
boolean result = str1.equalsIgnoreCase(str2); // trueImportant: Don't use == to compare strings - it compares object references, not content.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else