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);

String compareTo() method in jav

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.