05.0 Java Notes‎ > ‎Java: String‎ > ‎

Java String: compareTo()

Used to compare the values of two strings.
If the value returned for this method is ZERO, the strings compared are identical.
If the value returned for this method is NEGATIVE, the string compared to come before the string .
If the value returned for this method is POSITIVE, the string compared to comes after.

There are a number of compareTo style methods including compareToIgnoreCase(). See the Java API for more details.

Example:

"A".compareTo("B"); // yields -1

"B".compareTo("A"); // yields 1


word.compareTo(otherWord); // yields 0 if word and otherWord are the same.

// a negative number if word is before otherWord

// a positive number if word is after otherWord


Often compareTo() is used as a condition within a if or while loop
Example:

if (password.compareTo(passwordAttempt) == 0){
    runProgram();
}
else{
    loginAgain();
}

Comments