Wednesday, May 4, 2022

String Comparison in Java equals(), compareTo(), startsWith() Methods

In String class in Java there are number of methods provided to compare the Strings or the portion of the strings. This post shows some of the most used methods for comparing Strings in Java and also Java examples using these methods for comparing two strings.


String comparison using equals() and equalsIgnoreCase() methods

  • boolean equals(Object anObject)- This method is used to compare the content of two strings. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • boolean equalsIgnoreCase(String anotherString)- Comparison of strings using equals() method is case sensitive, if you want case considerations to be ignored then use equalsIgnoreCase method. When two strings are compared using this method they are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  String str1 = new String("This");
  System.out.println("String for comparison -- " + str.substring(0, 4));
  // Should be true
  System.out.println(str.substring(0, 4).equals("This"));
  // will be false, equals is case sensitive
  System.out.println(str.substring(0, 4).equals("this"));
  
  // returns true, case is ignored
  System.out.println(str.substring(0, 4).equalsIgnoreCase("this"));
  // returns true
  System.out.println(str1.equalsIgnoreCase("this"));
 }
}

Output

String for comparison -- This
true
false
true
true

Here original string is substringed to give a part of the String ("This"). That part is then used for comparison with another string (str1). Even when a new String is created which will have different reference, equals or equalsIgnoreCase will return true as content is matched here not reference.

String comparison using compareTo() and compareToIgnoreCase() methods

  • int compareTo(String anotherString)- Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
  • int compareToIgnoreCase(String str)- Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

In lexicographical comparison if two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.

If character is different at some position then, compareTo() returns the difference of the two character values. For example, if you are comparing run with sun then first char itself is different and difference between them is 1 so in that case -1 is returned.

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings.

To sum it up when two strings are compared using compareTo or compareToIgnoreCase methods, an integer value is returned which may be a positive or negative integer value or 0. Compared strings are equal if 0 is returned otherwise strings are not equal.

public class StringComparison {
  public static void main(String[] args) {
    String str1 = "run";
    String str2 = new String("run");
    String str3 = "gun";
    String str4 = "sun";
    
    //equal so returns 0
    System.out.println(str1.compareTo(str2));
    // Comparison with in a condition
    // that's how generally used 
    if(str1.compareTo(str2) == 0){
      System.out.println("str1 is equal to str2");
    }else{
      System.out.println("str1 is not equal to str2");
    }
      
    //str1 > str3 so returns positive integer
    System.out.println(str1.compareTo(str3));
    // with condition
    if(str1.compareTo(str3) > 0){
      System.out.println("str1 is greater than str3");
    }else{
      System.out.println("str1 is less than str3");
    }
    
    // str1 < str4 so returns negative integer
    System.out.println(str1.compareTo(str4));       
  }
}

Output

0
str1 is equal to str2
11
str1 is greater than str3
-1

String comparison using startsWith() and endsWith() methods

Using startsWith() and endsWith() methods you can compare a portion of a String.

  • boolean startsWith(String prefix)- Returns true if this string begins with the substring specified as an argument to the method.
  • boolean startsWith(String prefix, int offset)- Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
  • boolean endsWith(String suffix)- Returns true if this string ends with the substring specified as an argument to the method.
public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  // Should be true
  System.out.println(str.startsWith("This"));
  // test start at index 10, so returns true
  System.out.println(str.startsWith("test", 10));
  
  // returns false
  System.out.println(str.endsWith("test"));
  // returns true
  System.out.println(str.endsWith("test string"));
  // returns true
  System.out.println(str.endsWith("string")); 
 }
}

Output

true
true
false
true
true

Using regionMatches() method for String comparison

  • boolean regionMatches(int toffset, String other, int ooffset, int len)- Tests whether the specified region of this string matches the specified region of the String argument.
    Region is of length len and begins at the index toffset for this string and ooffset for the other string. This method is case sensitive.
  • boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)– Here first argument indicates whether case should be ignored; if true, case is ignored when comparing characters.
public class StringComparison {

 public static void main(String[] args) {
  String str1 = "This is an example string";
  String str2 = new String("example");
  String str3 = "Example";
  // returns true
  System.out.println(str1.regionMatches(11, str2, 0, str2.length()));
  // returns false
  System.out.println(str1.regionMatches(11, str3, 0, str3.length()));
  // returns true as case is ignored
  System.out.println(str1.regionMatches(true, 11, str3, 0, str3.length()));
 }
}

Output

true
false
true

Here in the first comparison using regionMatches() method the task is to compare "example" in string str1 with the string str2. Region extracted from String str1 starts at index 11 and length for the region is 7 which makes it "example". Comparison is to be done with the string str2 so that is the second argument. In str2 offset is 0. Here region to be compared is the complete length of string str2 so str2.length() method is used.

In second case everything is same except the matched string str3 which has the content "Example". Since method is case sensitive so returns false.

In third case first argument is passed as true so the case is ignored while comparing. That is why true is returned even when str1 and str3 are compared.

That's all for this topic String Comparison in Java equals(), compareTo(), startsWith() Methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. How to Reverse a String in Java
  3. Add Double Quotes to a String Java Program
  4. Is String Thread Safe in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Format Date in Java Using SimpleDateFormat
  2. Marker Interface in Java
  3. How and Why to Synchronize ArrayList in Java
  4. LinkedHashMap in Java With Examples
  5. How LinkedList Class Works Internally in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. Java LinkedBlockingQueue With Examples
  8. Interface Default Methods in Java

No comments:

Post a Comment