Z-A All Java Codes

Java String comapareTo() Code With Example

Table of Contents

Program

public class StringCompareTo
{
	public static void main(String[] args)
	{
		String s1 = "I";
		String s2 = "AM";
		String s3 = "GOOD";
		String s4 = "INDIAN";
		String s5 = "CITIZEN";
		System.out.println(s1.compareTo(s2));
		System.out.println(s2.compareTo(s3));
		System.out.println(s3.compareTo(s4));
		System.out.println(s4.compareTo(s5));
	}
}

Output

8
-6
-2
6    

Description

public int compareTo​(String anotherString)

this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings — that is, the value:
this.length()-anotherString.length()
For finer-grained String comparison, refer to Collator.

Specified by:

compareTo in interface Comparable

Parameters:

anotherString – the String to be compared.

Returns:

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.