Java Program to compare string using compareTo() method


The compareTo(obj) method compares this String to another Object.The value 0 is returned if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

We have the following two strings −

String str1 = "tom";
String str2 = "tim";

Let us check them for all the return values.

if(str1.compareTo(str2) > 0) {
 System.out.println("First string is greater!");
}
if(str1.compareTo(str2) == 0) {
 System.out.println("First string is equal to Second string!");
}
if(str1.compareTo(str2) < 0) {
 System.out.println("Second string is greater!");
}

The following is the final example.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str1 = "tom";
       String str2 = "tim";
       if(str1.compareTo(str2) > 0) {
          System.out.println("First string is greater!");
       }
       if(str1.compareTo(str2) == 0) {
          System.out.println("First string is equal to Second string!");
       }
       if(str1.compareTo(str2) < 0) {
          System.out.println("Second string is greater!");
       }
    }
}

Output

First string is greater!

Let us see another example.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String one = "This is demo text!";
       String two = new String("This text is for demo!");
       String three = new String("This is demo line!");
       String four = new String("The line is demo!");
       int res = one.compareTo( two );
       System.out.println(res);
       res = one.compareTo( three );
       System.out.println(res);
       res = one.compareTo( four );
       System.out.println(res);
    }
}

Output

-11
8
4

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements