Concept
How do you compare strings in Java?
ComputerScienceOne / Comparisons
"When comparing strings in Java, we cannot use the numerical comparison operators such as ==, or <. Because strings are objects, using these operators actually compares the variables’ memory addresses.\n\nString a = new String(\"Hello World!\");\n\nString b = new String(\"Hello World!\");\n\nif(a == b) {\n\nSystem.out.println(\"strings match!\");\n\n}\n\nThe code above will not print anything even though the strings a and b have the same content. This is because a == b is comparing the memory address of the two variables. Since they point to different memory addresses (created by two separate calls to the constructors) they will not be equal. Instead, the String class provides a compareTo() method that takes another string and returns something negative, zero, or something positive depending on the relative lexicographic ordering of the strings.\n\nint x;\n\nString a = \"apple\";\n\nString b = \"zelda\";\n\nString c = \"Hello\";\n\nx = a.compareTo(\"banana\"); //x is negative\n\nx = b.compareTo(\"mario\"); //x is positive\n\nx = c.compareTo(\"Hello\"); //x is zero\n\n//shorter strings precede longer strings:\n\nx = a.compareTo(\"apples\"); //x is negative\n\nString d = \"Apple\";\n\nx = d.compareTo(\"apple\"); //x is negative\n\nIn the last example, \"Apple\" precedes \"apple\" since uppercase letters are ordered before lowercase letters according to the ASCII table. We can also make case-insensitive comparisons using the compareToIgnoreCase() method which works the same way. Here, d.compareToIgnoreCase(\"apple\") will return zero as the two strings are the same ignoring the cases. Note that the commonly used equals() method only returns true or false depending on whether or not two strings are the same or different. They cannot be used to provide a relative ordering of two strings. This method is part of the String class due to the fact that strings implement the Comparable interface which defines a lexicographic ordering."
Related Ideas
- Why can’t numeric comparison operators be used to compare strings in Java?ComputerScienceOne · Comparing Strings and Characters
- How can you compare String values in Java?ComputerScienceOne · Tokenizing
- How does strcmp() compare the contents of two strings in C?ComputerScienceOne · Comparisons
- Why can’t numerical comparison operators be used to compare strings in C?ComputerScienceOne · Comparisons
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators
- How does PHP compare strings with case-sensitive and case-insensitive functions?ComputerScienceOne · Tokenizing
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How does PHP compare strings using strcmp()?ComputerScienceOne · Comparisons