Java String Compare

Filed Under: Java

Java String compare means checking lexicographically which string comes first. Sometimes it’s required to compare two strings so that a collection of strings can be sorted. For example, sorting students name so that it can be published in order and look good.

Java String Compare

java string compare
There are five ways to compare two strings.

  1. Using == operator
  2. Using equals() method
  3. Using compareTo() method
  4. Using compareToIgnoreCase() method
  5. Using java.text.Collator compare() method

Let’s look into each of these string comparison ways in detail.

Java String Comparison using == operator

When double equals operator is used to compare two objects, it returns true when they are referring to the same object, otherwise false. Let’s look at some code snippets for using == for string comparison in java.


String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
s3 = s3.intern();
System.out.println(s1 == s3); //true

As we know that when string literal is creating using double quotes, they go into String Pool. So s1 and s2 are actually referring to the same object in string pool, hence s1==s2 will return true.

When string is creating using new operator, it gets created in the heap space. So s1 and s2 are referring to different objects and hence s1==s3 will return false.

Next, when we are calling intern() method on s3, it returns the reference with same value from string pool. Since we already have “abc” in the string pool, s3 also gets the same reference. So finally s1==s3 will return true.

Java String Compare using equals() method

Note that String is immutable class, so it doesn’t make sense to compare them with == operator. When we are trying to compare the values of two string to be equal or not, better to use equals() method. If you are want to check for equality with case insensitivity, then you can use equalsIgnoreCase() method. Below code snippet shows examples of string comparison using equals() and equalsIgnoreCase() method.


String s1 = "abc";
String s2 = "abc";
String s3 = new String("ABC");
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //false
System.out.println(s1.equalsIgnoreCase(s3)); //true

Java String Comparison using compareTo() method

Sometimes we don’t want to check for equality, we are interested in which string comes first lexicographically. This is important when we want to sort the collection of strings in order of appearance in the dictionary. Java String class implements Comparable interface and compareTo() method is used to compare string instance with another string.

If this string precedes the argument passed, it returns negative integer otherwise positive integer. String compareTo() method returns 0 when both the strings are equal.

The comparison is based on the Unicode value of each character in the strings. 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. Assuming index ‘n’ is where characters are different then compareTo() will return this.charAt(n)-argumentString.charAt(n).

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo() method returns the difference of the lengths of the strings i.e. this.length()-argumentString.length().

Let’s look at some code snippets for java string compare using compareTo() method.


String str = "ABC";
System.out.println(str.compareTo("DEF")); //-3 (Integer.valueOf('A') - Integer.valueOf('D'))
System.out.println(str.compareTo("ABC")); //0 (equal string)
System.out.println(str.compareTo("abc")); //-32 (Integer.valueOf('A') - Integer.valueOf('a'))
System.out.println(str.compareTo("AB")); //1 (difference in length)

Just go through the above code snippets, they are easy to understand based on the concept explained above.

Java String Comparison using compareToIgnoreCase() method

Java String compareToIgnoreCase() method is similar to compareTo() method, except that case is ignored. Let’s look at a simple example where we will compare two input strings provided by user.


package com.journaldev.string;

import java.util.Scanner;

public class JavaStringCompare {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("Enter First String:");
		String first = sc.nextLine();
		System.out.println("Enter Second String:");
		String second = sc.nextLine();
		sc.close();

		System.out.println(first.compareTo(second));

		System.out.println(first.compareToIgnoreCase(second));

	}

}

Below image shows output of execution of above string comparison program.

java string comparison

Java String Comparison using Collator class

For locale specific comparison, we should use java.text.Collator class. The most important feature of Collator is the ability to define our own custom comparison rules. Let’s look at a simple example of using Collator for string comparison.


package com.journaldev.string;

import java.text.Collator;
import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.Locale;

public class JavaCollatorExample {

	public static void main(String[] args) throws ParseException {
		Collator collator = Collator.getInstance();
		Collator collatorFR = Collator.getInstance(Locale.FRANCE);

		System.out.println(collator.compare("X", "Z")); // -1
		System.out.println(collatorFR.compare("X", "Z")); // -1

		String rules = "< Z < X";
		RuleBasedCollator rbc = new RuleBasedCollator(rules);

		System.out.println(rbc.compare("X", "Z")); // 1
	}
}

Notice that "< Z < X" specifies a custom rule that Z comes before X apart from the natural ordering rule. That's why the output changed in the last comparison.

That's all for different ways to compare two strings in java program.

References: Collator API Doc, String API Doc

Comments

  1. Vijay Upadhyay says:

    Hi Pankaj
    I think there is some change in == comparison from Java 8. Ex
    public static void main(String[] args) {
    String s1 =”Java”;
    String s2 =”Java”;
    StringBuffer sb = new StringBuffer();
    sb.append(“Ja”);
    sb.append(“va”);
    System.out.println(“s1==s2: “+s1 ==s2);//T
    System.out.println(“s1 equals s2: “+s1.equals(s2));//T
    System.out.println(“sb.toString() == s1: “+sb.toString() == s1);//F
    System.out.println(“s1==s2: “+sb.toString().equals(s1));//T
    }
    But expected o/p is:
    false =====> this should be true but not
    s1 equals s2: true
    false
    s1==s2: true
    Please let me know if I am missing something.

    1. Pankaj says:

      You are confused because of operator precedence. Please check below output properly to get the idea.

      jshell> System.out.println("s1==s2: "+s1==s2);
      false
      
      jshell> System.out.println("s1==s2: "+(s1==s2));
      s1==s2: true
      

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages