JAVA program for string method compareTo()

JAVA program for string method compareTo()

This JAVA program for string method compareTo().

String method compareTo(String) compares the string object through which it is called and String object passed to this method. Returns 0 if the two strings are equal, returns positive if the first string is greater than the String object passed, else returns a negative value.

For two strings, str1.compareTo(str2)

  • if both strings have same content.
  • 1 if string1 is greater than string2 (checks for ASCII value)
  • -1 if string2 is greater than string1.

Program

import java.util.*;

class compareto
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the 1st string");
		String str1 = sc.nextLine();
		System.out.println("Enter the 2nd string");
		String str2 = sc.nextLine();
		System.out.println("On using .compareTo() we get:-");		
		System.out.println(str1+".compareTo("+str2+") = "+str1.compareTo(str2));
	}
}

Output

Share Me!