×

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax:
public int compareTo(String anotherString)
Parameters: anotherString: the String to be compared with the current String Returns: An integer value based on the case. compare two Strings i.e. s1 and s2 if s1 > s2, it returns positive number if s1 < s2, it returns negative number if s1 == s2, it returns 0 Java String compareTo() Example 1:
public class CompareToEx1
{ 
public static void main(String args[]){ 
         String s1="tutorial"; 
         String s2="Tutorial"; 
         String s3="tootorial"; 
         String s4="tutorial"; 
        String s5="tooturial"; 
       System.out.println(s1.compareTo(s2));
       System.out.println(s1.compareTo(s3));
       System.out.println(s1.compareTo(s4));//0 because both are equal    
      System.out.println(s1.compareTo(s5));
}
}
Output:
32
6
0
6
Java String compareTo() Example 2:
public class CompareToEx2
{
    public static void main(String[] args)
    {
        //compare a String
        String str = "Java TutorialAndExample";
        System.out.println("Compare To : " + str.compareTo("JAVA TUTORIALANDEXAMPLE"));
        //Compare a String with Ignore case
        System.out.println("Compare To : " + str.compareToIgnoreCase("JAVA TUTORIALANDEXAMPLE"));
    }
}
OUTPUT:
Compare To : 32
Compare To : 0
Java String compareTo() Example 3:
public class CompareToEx3 {
    public static void main(String[] args) {
        String s1,s2,s3,s4;
         s1 = "tutorial";
         s2 = "tutorial2";
         s3 = "TUTORIAL";
        System.out.println("String 1: " + s1);
        System.out.println("String 2: " + s2);
        System.out.println("String 3: " + s3);        
        // Compare the strings s1 and s2.  
        int S = s1.compareTo(s2);
        // Show the results of the comparison.  
        if (S < 0) { 
             System.out.println(s1 +"  is lexicographically greater than  " +  s2 );
          //compare the string s1 and s3 
           int s = s1.compareTo(s3.toLowerCase());
             if (s < 0) { 
             System.out.println( s1 +  " is lexicographically greater than " + s3 );
            } else if (s == 0) {
            System.out.println(s1 + " is lexicographically  equal to " + s3 );
        } else if (s > 0) {
            System.out.println( s1 + " is lexicographically less than " + s3 );
        } 
          } else if (S == 0) {
            System.out.println(s1 + " is lexicographically  equal to " +  s2 );
        } else if (S > 0) {
            System.out.println( s1 + " is lexicographically less than " +  s2 );
        } 
  }
Output:
String 1: tutorial
String 2: tutorial2
String 3: TUTORIAL
"tutorial" is lexicographically greater than "tutorial2"
"tutorial" is lexicographically  equal to "TUTORIAL"

Related Topics

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.