String Comparison In Java

Comparing strings is a fundamental aspect of Java development and plays a vital role in tasks such as verifying references, organizing data, and validating users. This segment will explore different methods for comparing strings in Java.

In Java, we have the ability to compare Strings based on their content and reference.

String comparison is utilized in various scenarios such as authentication, where the equals method is employed, sorting operations where the compareTo method is used, and reference matching which involves the == operator.

There are three ways to compare String in Java:

  • By Using equals Method
  • By Using == Operator
  • By compareTo Method
  • Using startsWith and endsWith Method
  • 1) By Using equals Method

The equals method of the String class is used to check for equality by comparing the actual content of the strings. It evaluates whether the values of the strings are the same. In addition to this, the String class offers two methods for this purpose. Moreover, the equalsIgnoreCase method can be utilized to perform a comparison that ignores the case of the characters.

The String class offers the following pair of methods:

  1. The method equals(Object another) is used to compare the current string with a specific object.
  2. The method equalsIgnoreCase(String another) is employed to compare the current string with another string while disregarding case sensitivity.

StringComparisonUsingEqualsMethod.java

Example

class StringComparisonUsingEqualsMethod{
 public static void main(String args[]){
   String s1="Sachin";
   String s2="Sachin";
   String s3=new String("Sachin");
   String s4="Saurav";
   System.out.println(s1.equals(s2));//true
   System.out.println(s1.equals(s3));//true
   System.out.println(s1.equals(s4));//false
 }
}

Output:

Output

true
true
false

Explanation

String objects S1 and S2 are connected to the string pool as they are declared as string literals. Consequently, when comparing S1 and S2 using the equals method, the result is true. In contrast, even though S3 is created using the new keyword, its content matches that of S1. As the equals method solely compares the contents of the strings, the comparison between S1 and S3 with equals results in true. On the other hand, comparing S1 and S4 using equals yields false due to the differing contents of S1 and S4.

Within the program mentioned above, the functionalities of the String class are utilized. The equals function confirms a match between String objects only if both strings are in the same case. On the other hand, equalsIgnoreCase validates a match irrespective of the letter cases of the strings.

StringComparisonUsingequalsIgnoreCase.java

Example

class  StringComparisonUsingequalsIgnoreCase {
    public static void main(String[] args) {
        String s1 = "Ram";
        String s2 = "rAm";
        // Using equals() method for case-sensitive comparison
        boolean equalsResult = s1.equals(s2);
        System.out.println("Using equals() method: " + equalsResult); // Output: false
        // Using equalsIgnoreCase() method for case-insensitive comparison
        boolean equalsIgnoreCaseResult = s1.equalsIgnoreCase(s2);
        System.out.println("Using equalsIgnoreCase() method: " + equalsIgnoreCaseResult); // Output: true
    }
}

Output:

Output

false
true

Explanation

Two distinct strings, s1 and s2, are provided with different cases ("Ram" and "rAm").

Utilize the equals method to compare the strings s1 and s2. Due to the difference in cases, this function conducts a case-sensitive comparison and will result in a false outcome.

To compare strings s1 and s2 without considering case sensitivity, the equalsIgnoreCase method is utilized. This method results in a true value as it treats the content equally while disregarding any differences in letter case.

2) By Using == Operator

In Java, the == operator evaluates references instead of values.

StringCompare.java

Example

class StringCompare {
    public static void main(String[] args) {
        String s1 = "Kohli";
        String s2 = "Kohli";
        String s3 = new String("Kohli");
        System.out.println(s1 == s2);              // true 
        System.out.println(s1 == s3);              // false
    }
}

Output:

Output

true
false

3) String compare by compareTo Method

The compareTo function of the String class compares values based on their lexicographical order and outputs an integer value indicating whether the first string is less than, equal to, or greater than the second string.

Suppose s1 and s2 are two String objects. If:

  • s1 == s2 : The method returns 0.
  • s1 > s2 : The method returns a positive value.
  • s1 < s2 : The method returns a negative value.

StringComparisonUsingComapreto.java

Example

class StringComparisonUsingComapreto {
    public static void main(String[] args) {
       String str1 = "Sachin";
        String str2 = "Sachin";
        String str3 = "Ratan";
        System.out.println(str1.compareTo(str2));      // 0
        System.out.println(str1.compareTo(str3));      // 1 (str1 > str3)
        System.out.println(str3.compareTo(str1));      // -1 (str3 < str1)
    }
}

Output:

Output

0
1
-1

Explanation

The variable str1 and str2 hold the identical value "Sachin," whereas str3 contains the word "Ratan."

4) Using startsWith and endsWith Methods

To identify whether a string commences with a specific prefix and concludes with a designated suffix, you can utilize the functions startsWith to check the beginning and endsWith to verify the ending of the string.

Example

class StringCompare {
    public static void main(String[] args) {
        String str = "String Compare";
        System.out.println(str.startsWith("String")); // true
        System.out.println(str.endsWith("Compare"));  // true
    }
}

Output:

Output

true
true

Explanation

The function startsWith("Hello") will return a boolean value of true if the string it operates on begins with the specified prefix.

The function endsWith("World!") will evaluate to true if the provided string indeed finishes with the specified suffix.

Conclusion

In essence, the compareTo method provides a way to compare strings based on their lexicographical sequence. By understanding the return values (0, positive, or negative), developers can determine the relative order of two strings. The illustration demonstrates how the method functions with different string inputs.

String Comparison in Java MCQ

  1. Which of the following statements is true about the equals method and the == operator when comparing strings in Java?
  • equals compares the references of the strings, while == compares the content of the strings.
  • equals and == both compare the content of the strings.
  • equals compares the content of the strings, while == compares the references.
  • equals and == both compare the references of the strings.

The equals function is employed to assess whether the content of two string instances is identical, whereas the == operator determines whether the two references are pointing to the same object in the computer's memory.

  1. What outcome does the code below produce?
  2. Example
    
    String s1 = "Hello";
    String s2 = new String("Hello");
    String s3 = "Hello";
    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));
    System.out.println(s1 == s3);
    
  • false, true, false
  • true, false, true
  • false, true, true
  • true, true, false

In this scenario, the statement s1 == s2 evaluates to false because s1 and s2 point to distinct objects. However, when using the method s1.equals(s2), it returns true since their contents are identical. On the other hand, the comparison s1 == s3 yields true because both s1 and s3 point to the identical string literal stored in the string pool.

Example

String s1 = "Java";
String s2 = "java";
System.out.println(s1.compareTo(s2));
  • Positive integer
  • Negative integer
  • Compilation error

Explanation: The compareTo method compares strings lexicographically. Since uppercase 'J' has a lower Unicode value than lowercase 'j', s1.compareTo(s2) returns a positive integer.

  1. Which method should be used to perform a case-insensitive comparison of two strings in Java?
  • compareTo
  • equalsIgnoreCase
  • compareToIgnoreCase
  • equals

The method equalsIgnoreCase is utilized to compare two strings while disregarding any variations in case. This method is ideal for conducting equality checks that are insensitive to case differences.

What result will the provided code snippet produce?

Example

String s1 = "apple";
String s2 = "Apple";
String s3 = new String("apple");
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1 == s3);
  • false, false, true
  • false, true, false
  • true, true, true
  • true, false, false

When comparing strings using s1.equals(s2), the result is false due to differing cases. In contrast, s1.equalsIgnoreCase(s2) returns true as it disregards case discrepancies. It's important to note that s1 == s3 evaluates to false because despite having identical contents, s1 and s3 point to distinct objects.

Input Required

This code uses input(). Please provide values below: