The String
class in Java offers various different methods for comparing strings and substrings. Let’s see some of the comparison tools from Java’s most important built-in class, String
.
equals()
and equalsIgnoreCase()
The equals()
method is used to compare the equality of both the strings. This comparison is case sensitive, but if we want to compare two strings irrespective of their case differences, then we use the equalsIgnoreCase()
method.
"Hello".equals("Hello") //true
"Hello".equalsIgnoreCase("HELLO") //true
regionMatches()
The regionMatches()
method is used to compare a specific region in one string with a specific region in another string. Java also offers an overloaded form that helps us to compare strings while ignoring their case differences.
"Hello World".regionMatches(6, "world", 0, 4) //false
"Hello World".regionMatches(true, 6, "world", 0, 4) //true
startsWith()
and endsWith()
The startsWith()
method helps us check whether a given string begins with a specific substring, whereas; endsWith()
is used to check whether a given string ends with the specific substring given. This can also be referred to as a specialized form of regionMatches()
.
This method is case sensitive.
"Hello".startsWith("He") //true
"Hello".endsWith("lo") //true
equals()
vs. ==
We often get confused while using equals()
and ==
, but they are used to perform two different operations.
The equals()
method is used to compare the characters inside a string object; whereas, the ==
operator is used to compare two object references to see whether they refer to the same instance.
String str1 = "Hello";
String str2 = new String(str1);
String str3 = "Hello";
str1.equals(str2) //true
str1 == str2 //false
str1 == str3 //true
compareTo()
The compareTo()
method is used to know whether or not strings are identical. The following integer values are returned:
A string is said to be greater when it comes after the other in the dictionary, and lesser when it comes before the other in the dictionary.
This method is case sensitive.
"Hello".compareTo("Hello") //0
"hello".compareTo("Hello") //32