All the Rules

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") positve
"rugrat" .compareTo ("rugRat") positve
"ant" .compareTo ("turtle") negative
"toadstool" .compareTo ("total") negative
"ABCDEFG" .compareTo ("ABcD") negative

All the Rules

Here are all the rules for comparing strings, in one annoying list:

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.

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

Rule 3: Otherwise, find the first differing pair of characters in the strings A and B. Call them Achar and Bchar. Then A.compareTo(B) is negative if Achar comes before Bchar in the alphabet used by Java (and otherwise is positive).

The rules about what character comes first in the alphabet depend on what country you are in. This is one of the aspects of internationalization, which is the subject of customizing programs for use in different countries. Lets not worry about that.

QUESTION 9:

Of course, you would like to practice this:

"turtle" .compareTo ("turtledove")
"polarbear" .compareTo ("polarbear")
"freezing point" .compareTo ("freezing")
"Power" .compareTo ("power")
"FORTRAN" .compareTo ("fortran")