Comparing Strings

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

No. Upper and lower case matter in string comparisons.

Comparing Strings

Upper case characters are regarded as less than lower case characters. So "APPLE".compareTo("apple") returns a negative integer.

When strings are compared, case-sensitive dictionary order is used. Mostly this means that when two strings of the same case are compared, the one that appears first in the dictionary is less than the other. The technical term for this is lexicographic order. Here are the details:

Rule 1: If A.compareTo(B) == 0, then A and B are the same length (counting all characters, including blanks and punctuation) and each character in A is identical (including case) to the character in B at the same location.

"batcave".compareTo("batcave") == 0
"batcave".compareTo("bat cave") != 0

There are more rules on the following pages ...

QUESTION 6:

Decide which strings, when used with compareTo() return zero.

"bugbear" .compareTo ("bugbear")
"bugbear" .compareTo ("Bugbear")
"Zorba" .compareTo ("Zorba!")
"mushroom" .compareTo ("mush room")
"TOAD" .compareTo ("TOAD")