Comparing Strings
In this section, we will see how to compare strings. This will let us see if two strings have the same
characters (are equal) and how they compare alphabetically (to see if one “comes before”
or “comes after” another). When we have compared other types (like ints), we have used ==, <,
>, <=, >=, etc. – however, this operators will not work the way we want with strings. When we
try to use those operators, we will actually be comparing the memory address of the two strings –
we want to compare their characters.
Equality
To see if two strings have the same characters, we will use the equals command. Here is an
example:
String s1 = "hello";
String s2 = "hello";
if (s1.equals(s2))
{
System.out.println("same");
}This example compares the strings s1 and s2. If they contain exactly the same characters, the
equals command will evaluate to true. Otherwise, it will evaluate to false. Equals does NOT
ignore the case of characters, so it will think that “hello” and “Hello” are not equal.
Ordering alphabetically
To how two strings would be ordered alphabetically, we will use the compareTo command. Here is an example:
String s1 = "apple";
String s2 = "banana";
if (s1.compareTo(s2) < 0)
{
System.out.printf("%s comes before %s%n", s1, s2);
}This example is looking to see if s1 comes alphabetically before s2. Since “apple” comes
before “banana”, the if-statement is true. In general, if we do:
s1.compareTo(s2)The result will be:
0, if s1 equals s2
<0, if s1 comes alphabetically before s2
>0, if s1 comes alphabetically after s2