String Comparison Methods Overview
The String class includes a number of methods that compare strings or substrings within strings. Several are examined in this post.- equals(Object anObject)
- equalsIgnoreCase(String str)
- regionMatches( )
- startsWith( ) methods
- endsWith( ) methods
- equals( ) Versus ==
- compareTo( )
- compareToIgnoreCase(String str)
String Comparison Methods with Examples
equals(Object anObject)
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive.
Example 1: This example demonstrates the usage of the equals() method.
public class EqualsExample {
public static void main(String[] args) {
String str = "javaguides";
String str1 = "javaguides";
String str3 = "javatutorial";
boolean equal = str.equals(str1);
System.out.println(" Is both string are equal :: " + equal);
}
}
Output:
Is both string are equal :: true
equalsIgnoreCase(String str) Method
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise.
Example: This example demonstrates the usage of the equalsIgnoreCase() method.
public class EqualsIgnoreCaseExample {
public static void main(String[] args) {
String str = "javaguides";
boolean equal = str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: " + equal);
}
}
Output:
Strings are equal :: true
Here is an example that demonstrates both equals( ) and equalsIgnoreCase( ):
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
regionMatches() methods
There are two types of regionMatches() methods.
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) - Tests if two string regions are equal. regionMatches(int toffset, String other, int ooffset, int len) - Tests if two string regions are equal.
Example: Example to tests if two string regions are equal.
public class RegionMatchesExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "guides";
boolean b = str.regionMatches(0, subStr, str.length(), str.length());
boolean b1 = str.regionMatches(true, 0, str, 0, str.length());
System.out.println(b);
System.out.println(b1);
}
}
Output:
false
true
startsWith() methods
There are two forms of startsWith() methods.
startsWith(String prefix) - Tests if this string starts with the specified prefix. boolean startsWith(String prefix, int toffset) - Tests if the substring of this string beginning at the specified index starts with the specified prefix.
The startsWith( ) method determines whether a given String begins with a specified string.
Example: This is a complete example to demonstrate the usage of startsWith() methods.
public class StartsWithExample {
public static void main(String[] args) {
String str = "javaguides";
boolean startWith = str.startsWith("ja");
System.out.println("startWith :: " +startWith);
// Remember index starts from 0
boolean startWithOffset = str.startsWith("guides", 4);
System.out.println("startWithOffset :: " + startWithOffset);
}
}
Output:
startWith :: true
startWithOffset :: true
endsWith(String suffix)
This method tests if this string ends with the specified suffix. Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise.
Example:
public class EndsWithExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "guides";
boolean endsWith = str.endsWith(subStr);
System.out.println(str + " endsWith " + subStr +" :: " + endsWith);
}
}
Output:
javaguides endsWith guides :: true
It is important to understand that the equals( ) method and the == operator perform two different operations.
- The equals( ) method compares the characters inside a String object.
- The == operator compares two object references to see whether they refer to the same instance.
The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:
Hello equals Hello -> true
Hello == Hello -> false
compareTo(String anotherString)
Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in the dictionary order. A string is greater than another if it comes after the other in the dictionary order.
The method compareTo( ) serves this purpose. It is specified by the Comparable interface, which String implements. It has this general form:
The method compareTo( ) serves this purpose. It is specified by the Comparable interface, which String implements. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is returned as values meaning:
- Less than zero The invoking string is less than str.
- Greater than zero The invoking string is greater than str.
- Zero The two strings are equal.
Example: Here is a sample program that sorts an array of strings. The program uses compareTo( ) to determine sort ordering for a bubble sort:
// A bubble sort for Strings.
public class CompareToSecondExample {
static String arr[] = { "Now", "is", "the", "time",
"for", "all", "good", "men", "to", "come", "to", "the", "aid",
"of", "their", "country" };
public static void main(String args[]) {
for (int j = 0; j < arr.length; j++) {
for (int i = j + 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
As you can see from the output of this example, compareTo( ) takes into account uppercase and lowercase letters. The word "Now" came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set.
Example: compareTo method return different values example
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Java";
String s4 = "Guides";
System.out.println(s1.compareTo(s2));// 0 because both are equal
System.out.println(s1.compareTo(s3));// -2 because "H" is 2 times lower than "J"
System.out.println(s1.compareTo(s4));// 1 because "G" is 1 times greater than "H"
Output:
0
-2
1
Example: Compare the string with black or empty string using the compareTo() method. Note that compared with an empty string, returns the length of the string.
String s1 = "hello";
String s2 = "";
String s3 = "me";
// compare with empty string, returns length of the string
System.out.println(s1.compareTo(s2));
// If first string is empty, result would be negative
System.out.println(s2.compareTo(s3));
Output:
5
-2
compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.
Example:
String s1="Hello World";
String s2="hello world";
String s3="Java";
String s4="java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));
Output:
0
0
This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
GitHub Repository
Reference
Strings Related Posts
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course