Last active
November 19, 2015 02:21
-
-
Save au5ton/a990176c70560eeba765 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AlphabeticalComparison { | |
public static void main(String[] args) { | |
System.out.println("apple".compareTo("orange")); //Gives back a negative number because "apple" comes before "orange" alphabetically | |
System.out.println("orange".compareTo("apple")); //Gives back a positive number because "orange" comes after "apple" alphabetically | |
//Note that .compareTo() doesn't ignore cases. A word with an uppercase character will appear *before* a letter earlier in the alphabet | |
//(because the alphabet is actually the unicode table) | |
//Unicode table for English alphabet | |
//ABCDEFGHIJKLMNO0050PQRSTUVWXYZ[\]^_`abcdefghijklmno0070pqrstuvwxyz | |
// ^ ^ | |
// | | | |
// | 'c' comes second | |
// 'Z' comes first | |
//An exmaple of this: | |
System.out.println("Zebra".compareTo("carrot")); //Gives back a negative number because "Zebra" (with a capital Z) comes before "carrot" (with a lowercase c) in unicode | |
//Even though, in English, Zebra would be put after carrot alphabetically | |
//To fix this, you can use a different method that does the same thing as String.compareTo() | |
System.out.println("Zebra".compareToIgnoreCase("carrot")); //Run this, and you'll get a positive number because "Zebra" comes after "carrot" when you ignore cases | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment