Studyon Minte9.com
Java SE




Compare



Often, it is not enough to simply know whether two strings are identical. 
For sorting applications, you need to know which is less than, equal to, or greater than the next. 
A string is less than another if it comes before the other in dictionary order.

CompareTo returns the difference of the ASCII codes of the first non-matching character.


package testexample; public class Test { public static void main(String[] args) { int c; // --- Strings are the same --- // c = "He is pixelated".compareToIgnoreCase("He is pixelated"); System.out.println(c); // Outputs: 0 // --- Strings differs by e -> a (edbc = 4) --- // c = "He is pixalated".compareToIgnoreCase("He is pixelated"); System.out.println(c); // Outputs: -4 (e -> a : dcba) // --- Strings differs by 1 --- // c = "He is pixalated".compareToIgnoreCase("He is pixalated."); System.out.println(c); // Outputs: -1 // --- Strings differs by E -> a --- // c = "He is pixAAAAAAAAAAAlated".compareToIgnoreCase("He is pixelated"); System.out.println(c); // Outputs: -4 (e -> a : edcb) // --- Strings differs by p -> Z ( prstuqvxyw = 10 --- // c = "He is Zpixalated".compareToIgnoreCase("He is pixelated"); System.out.println(c); // Outputs: 10 } }
 


http://www.java-samples.com/showtutorial.php?tutorialid=220