×

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

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java Integer toOctalString() method

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

1 minute read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.