Java – compare strings

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));
    }
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1496
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

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));
    }
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1508
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments