To compare strings alphabetically in Java, use the
compareToIgnoreCase
method.A.compareToIgnoreCase(B)
returns a negative number when A
precedes B
.
int result = "Amanda".compareToIgnoreCase("Sally");
System.out.println(result); // -18
System.out.println(result < 0 ? "Amanda is before Sally" : "Amanda is after Sally"); // Amanda is before Sally
A.compareToIgnoreCase(B)
returns a positive number when A
follows B
.
int result = "Zack".compareToIgnoreCase("Wendy");
System.out.println(result); // 3
System.out.println(result < 0 ? "Zack is before Wendy" : "Zack is after Wendy"); // Zack is after Wendy