Case sensitive comparison
Compare strings using firstString.compareTo(secondString). Positive outcome means firstString > secondString and so on.
public class Main { public static void main(String[] args) { String firstStr = "def"; String[] secondStrArr = {"abc", "def", "efg", "DEF"}; System.out.println("firstStr | secondStr | firstStr.compareTo(secondStr)"); for (String secondStr: secondStrArr) { System.out.println(firstStr + " | "+ secondStr + " | " + firstStr.compareTo(secondStr)); } } }
firstStr | secondStr | firstStr.compareTo(secondStr) def | abc | 3 def | def | 0 def | efg | -1 def | DEF | 32
Case insensitive comparison – compareToIgnoreCase
public class MainIgnoreCase { public static void main(String[] args) { String firstStr = "def"; String[] secondStrArr = {"abc", "def", "efg", "DEF"}; System.out.println("firstStr | secondStr | firstStr.compareToIgnoreCase(secondStr)"); for (String secondStr: secondStrArr) { System.out.println(firstStr + " | "+ secondStr + " | " + firstStr.compareToIgnoreCase(secondStr)); } } }
firstStr | secondStr | firstStr.compareToIgnoreCase(secondStr) def | abc | 3 def | def | 0 def | efg | -1 def | DEF | 0