Nearly Same Strings, but Different Lengths

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:

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

Nearly Same Strings, but Different Lengths

If the strings are not identical, you have to decide which one is less than the other. Sometimes this depends only on the length of the strings.

Rule 2: Otherwise, if string A is a prefix of string B, then A.compareTo(B) < 0.

"bat".compareTo("batcave") < 0
"apple".compareTo("applesauce") < 0
"BAT".compareTo("BATCAVE") < 0

If it is the first string that is longer, then that string is greater than the other:

"batcave".compareTo("bat") > 0
"applesauce".compareTo("apples") > 0
"BATCAVE".compareTo("BAT") > 0

In using this rule you need to pay attention to case. "BAT" is not a prefix of "batcave".

There are yet more rules ....

QUESTION 7:

Decide on the value returned by compareTo():

"bugbear" .compareTo ("bugbear")
"bug" .compareTo ("bugbear")
"pepper" .compareTo ("peppermint")
"toadstool" .compareTo ("toad")
"cat" .compareTo ("caterpillar")