String compareTo() method in java

In this post we will see String compareTo() method in java.

String compareTo() method in java

  1. Some basic points and Signature of compareTo(Object o) method.
  2. What is lexicographically comparison of two String?
  3. How does comapreTo(Object o) work in String?
  4. How to override compareTo(Object o) method?
  5. How to define custom compareTo() method.
  6. Use of compareTo(Object o) in real time project.

 

String compareTo() method in java

Some basic points and Signature of compareTo(Object o) method.

This method defined in the Comparable interface which returns an int value that can be a negative number, zero or positive number  This method is overridden in String class which is used to compare two String lexicographically.

public int compareTo(Object o);

 

What is lexicographically comparison of two String? 

Let’s understand lexicographically meaning with an example. Suppose we have two characters ‘a’ and ‘c’, ‘a’ comes before ‘c’, this is called the lexicographical order.  Again the question may come, why we are not calling this alphabetical order? a and c are nothing but alphabet only, when we say lexicographically order we mean to say something more than alphabet like some special character too.

Let’s see how compareTo(Object 0) return int value. Suppose we two String s1 = “am” and String s2 = “bm”.

  • if (s1 > s2) it returns a positive number.
  • if both the strings are equal, it returns 0.
  • if (s1< s2) it returns a negative number.

String compareTo() method in java

How does comapreTo(Object o) work in java?


We have a basic idea that compareTo() will return positive, zero or negative number. Here we will see how it decide which number it has to return. Let’s see an example –

Example 1 – 

public class ComareToExample1 {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "bcd";
		System.out.println(s1.compareTo(s2));
	}
}

Output is –   -1

The output of the above program is -1. It will compare the first character of s1 and s2, which is a and b. It will check the ASCII value of a and b which is 97 and 98, since we are doing s1.comapreTo(s2) it will calculate 97-98 which is -1. So, what about the rest of characters(i.e bc and cd), will it check for those characters, no it will not check because we have a different character in beginning only(s1 has a and s2 has b). Before going forward let’s have a look in the ASCII table, which will help us to discuss further.

CharacterASCII ValueCharacterASCII Value
a97A65
b98B66
c99C67
d100D68
e101E69
f102F70
g103G71
h104H72
i105I73
j106J74
k107K75
l108L76
m109M77
n110N78
o111O79
p112P80
q113Q81
r114R82
s115S83
t116T84
u117U85
v118V86
w119W87
x120X88
y121Y89
z122Z90

 

Example 2 – 

public class CompareToExample2 {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "ade";
		System.out.println(s1.compareTo(s2));
	}
}

Output is –  -2

The output of the above program is -2. Let’s see how. s1 is referring to “abc” and s2 is referring to “ade”, in this first character is same so it will compare next character i.e b and d. ASCII value of b and d is 98 and 100 respectively and we are comparing s1.compareTo(s2), it will calculate 98-100 and result is -2. Again what will happen if we do s2.compareTo(s1), the result will be  2.

Example 3 – 

public class CompareToExample3 {
	public static void main(String[] args) {
		String s1 = "Abc";
		String s2 = "ade";
		System.out.println(s1.compareTo(s2));
	}
}

Output is –   -32

s1 is referring to “Abc” and s2 is referring “abc”, ASCII value of A is 65 and ASCII value of a is 97. The calculation will be something like 65-97 which is -32.

Example 4 – 



public class CompareToExample2 {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "abc";
		System.out.println(s1.compareTo(s2));
	}
}

Output is – 0

It will compare all character, will check for ASCII value and finally it will return 0.

How to override compareTo(Object o) method?

comapreTo() method is defined in the Comparable interface and overridden in String class. We can also override compareTo() method with some custom logic, we need to implement the Comparable interface. When we sort list object using Comparable interface, we override compareTo() method and write some custom logic. For more details please visit this post.

 

How to define custom compareTo() method.

Sometime in the interview people like to ask can we define custom compareTo() method, if yes how. Here we will define custom compareTo() method. Let’s see below example –

public class CustomCompareTo {

	public char[] m1() {
		char chararr[] = new char[3];
		chararr[0] = 'a';
		chararr[1] = 'a';
		chararr[2] = 'm';
		return chararr;
	}

	public int ourCustomCompareTo(String anotherString) {
		int length1 = m1().length;
		int length2 = anotherString.length();
		int lim = Math.min(length1, length2);
		char char1[] = m1();
		char char2[] = anotherString.toCharArray();

		int i = 0;
		while (i < lim) {
			char ch1 = char1[i];
			char ch2 = char2[i];
			if (ch1 != ch2) {
				return ch1 - ch2;
			}
			i++;
		}
		return length1 - length2;
	}

	public static void main(String[] args) {
		CustomCompareTo t = new CustomCompareTo();
		System.out.println("comparing of two String using custom compare to method : -  "+t.ourCustomCompareTo("cam"));
		System.out.println("--------------------------");
		String s1 = "aam";
		String s2 = "cam";
		System.out.println("comparing of two String using compareTo() method : - "+s1.compareTo(s2));
	}
}

Output is –

comparing of two String using custom compare to method : – -2
————————–
comparing of two String using compareTo() method : – -2

In above program we have defined one string as hardcoded value, we can make it dynamic.

 

Use of compareTo(Object o) in real time project. 

Please visit this post.

That’s all about String compareTo() method in java.

You may like.