Java String Comparison: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-04 04:50:23   6973  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

The String class includes several methods that compare strings or substrings within strings. Each is examined here.

There are three ways to compare string in java:

  1. By equals() method
  2. By = = operator
  3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:

Methods Description
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another)  compares this String to another string, ignoring case.

Program: equals

class Stringcomparison{

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

Output

true
true
false
Press any key to continue . . .

Program: equalsIgnoreCase

class Teststringcomparison{
 public static void main(String args[]){
   String s1="RAMBO";
   String s2="rambo";

   System.out.println(s1.equals(s2));//false
   System.out.println(s1.equalsIgnoreCase(s2));//true
 }
}

Output

false
true
Press any key to continue . . .

More examples Program

Following example compares two strings by using str compareTo(string), str compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the ascii difference of first odd characters of compared strings.

Program

public class StringCompare{
   public static void main(String args[]){
      String str = "Hello Rambo";
      String anotherString = "hello rambo";
      Object objStr = str;

      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

Output

The above code sample will produce the following result.

-32
0
0
Press any key to continue . . .

2) String compare by == operator

This operators that can be used with object references are comparing for equality (==). These operators compare two values to see if they refer to the same object. Although this comparison is very fast,

Program

class Stringcomparison {
 public static void main(String args[]){
   String s1="Atnyla";
   String s2="Atnyla";
   String s3=new String("Atnyla");
   System.out.println(s1==s2);//true (because both refer to same instance)
   System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
 }
}

Output

The above code sample will produce the following result.

true
false
Press any key to continue . . .

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:

  • stng1 == stng2 :0
  • stng1 > stng2   :positive value
  • stngs1 < stng2   :negative value

Program

class Stringcomparison {
 public static void main(String args[]){
   String stng1="Atnyla";
   String stng2="Atnyla";
   String stng3="Rambo";
   System.out.println(stng1.compareTo(stng2));//0
   System.out.println(stng1.compareTo(stng3));//1(because stng1>s3)
   System.out.println(stng3.compareTo(stng1));//-1(because stng3 < s1 )
 }
}

Output

0
-17
17
Press any key to continue . . .

Equality comparison: One way for primitives, Four ways for objects

Comparison Primitives Objects
a == ba != b Equal values Compares references, not values. The use of == with object references is generally limited to the following:
  • Comparing to see if a reference is null.
  • Comparing two enum values. This works because there is only one object for each enum constant.
  • You want to know if two references are to the same object
a.equals(b) N/A Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

It turns out that defining equals() isn't trivial; in fact it's moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann's Core Java Vol 1. [TODO: Add explanation and example]

a.compareTo(b) N/A Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
compare(a, b) N/A Comparator interface. Compares values of two objects. This is implemented as part of the Comparator interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following.
  • Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort()method.
  • System class. To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
  • Strategy pattern. To implement a strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.

If your class objects have one natural sorting order, you may not need this.

MCQ Available

There are 1 MCQs available for this topic.

1 MCQ