Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Java long compareTo() with examples
Next article icon

Java String compareTo() Method with Examples

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Strings in Java are objects that are supported internally by an array only which means contiguous allocation of memory for characters.  Please note that strings are immutable in Java which means once we create a String object and assign some values to it, we cannot change the content. However, we can create another String object with the modifications that we want.

The String class of Java comprises a lot of methods to execute various operations on strings and we will be focusing on the Java String compareTo() method in this article.

Java String.compareTo() Method

The Java compareTo() method compares the given string with the current string lexicographically. It returns a positive number, a negative number, or 0. It compares strings based on the Unicode value of each character in the strings.

Example:

Java
public class StringCompareTo {      public static void main(String[] args) {         String str1 = "Geeks";         String str2 = "Geeks";          int comparison = str1.compareTo(str2);          if (comparison < 0) {             System.out.println(str1 + " comes before " + str2 + " lexicographically.");         } else if (comparison > 0) {             System.out.println(str1 + " comes after " + str2 + " lexicographically.");         } else {             System.out.println(str1 + " and " + str2 + " are lexicographically equal.");         }     } } 

Output:

Geeks and Geeks are lexicographically equal.

Syntax

int comparison = str1.compareTo(str2);

Parameters:

  • str1: String 1 for comparison
  • str2: String 2 for comparison

Returns:

  • if string1 > string2, it returns positive number
  • if string1 < string2, it returns negative number
  • if string1 == string2, it returns 0

Exception: It throws following two exceptions:

  • NullPointerException- if the specified object is Null.
  • ClassCastException- if current object can’t be compared with specified object.

Variants of CompareTo() Method

There are three variants of the compareTo() method which are as follows:

  1. Using int compareTo(Object obj)
  2. Using int compareTo(String AnotherString)
  3. Using int compareToIgnoreCase(String str)  

1. int compareTo(Object obj)

This method compares this String to another Object.

Syntax: 

int compareTo(Object obj)

Parameters: 

  • obj: the Object to be compared.

Return Value: The value 0 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.

Example:

Below is the implementation of int compareTo(Object obj):

Java
public class Player implements Comparable<Player> {     private String name;     private String gender;     private String country;      public Player(String name, String gender, String country) {         this.name = name;         this.gender = gender;         this.country = country;     }      @Override     public int compareTo(Player other) {         return this.name.compareTo(other.name);     }      // Getters and Setters for name, gender, and country     public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public String getGender() {         return gender;     }      public void setGender(String gender) {         this.gender = gender;     }      public String getCountry() {         return country;     }      public void setCountry(String country) {         this.country = country;     }      // toString method to display the object     @Override     public String toString() {         return "Player{" +                 "name='" + name + '\'' +                 ", gender='" + gender + '\'' +                 ", country='" + country + '\'' +                 '}';     }      public static void main(String[] args) {         Player player1 = new Player("Ravi Napit", "Male", "India");         Player player2 = new Player("John Doe", "Male", "USA");          // Correct comparison         System.out.println(player1.compareTo(player2));          System.out.println(player2.compareTo(player1));         System.out.println(player1.compareTo(player1));          // Incorrect comparison that will cause a compile-time error         // Uncommenting the following line will cause an error         // System.out.println("Ravi Napit".compareTo(player1));     } } 

Output
-1 1 0 

Remember: This method may sometimes give error for incompatible types as sometimes objects cannot be converted to java.lang.String.

2. int compareTo(String anotherString) 

This method compares two strings lexicographically. 

Syntax: 

int compareTo(String anotherString)

Parameters: 

  • anotherString: the String to be compared.

Return Value: The value 0 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.

Example:

Below is the implementation of int compareTo(String anotherString):

Java
// Java code to demonstrate the // working of compareTo()  public class Cmp2 {     public static void main(String args[])     {          // Initializing Strings         String str1 = "geeksforgeeks";         String str2 = "geeksforgeeks";         String str3 = "astha";          // Checking if geeksforgeeks string         // equates to geeksforgeeks string         System.out.print(             "Difference of geeksforgeeks(str) and geeksforgeeks(str) : ");         System.out.println(str1.compareTo(str2));          // Checking if geeksforgeeks string         // equates to astha string         System.out.print(             "Difference of astha(str) and geeksforgeeks(str) : ");         System.out.println(str1.compareTo(str3));     } } 

Output
Difference of geeksforgeeks(str) and geeksforgeeks(str) : 0 Difference of astha(str) and geeksforgeeks(str) : 6

3. int compareToIgnoreCase(String str)  

This method compares two strings lexicographically, ignoring case differences. 

Syntax:

int compareToIgnoreCase(String str)

Parameters: 

  • str: the String to be compared.

Return Value: This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Example:

Below is the implementation of int compareToIgnoreCase(String str):

Java
// Java code to demonstrate the // working of compareToIgnoreCase()  public class Cmp3 {     public static void main(String args[])     {          // Initializing Strings         String str1 = "geeks";         String str2 = "gEEkS";          // Checking if geeksforgeeks string         // equates to geeksforgeeks string         // case sensitive         System.out.print(             "Difference of geeks and gEEkS (case sensitive) : ");         System.out.println(str1.compareTo(str2));          // Checking if geeksforgeeks string         // equates to astha string         // case insensitive         // using compareToIgnoreCase()         System.out.print(             "Difference of geeks and gEEkS (case insensitive) : ");         System.out.println(str1.compareToIgnoreCase(str2));     } } 

Output
Difference of geeks and gEEkS (case sensitive) : 32 Difference of geeks and gEEkS (case insensitive) : 0

Exceptions in Java String compareTo() Method

compareTo() method in Java can raise two possible exceptions:

  • NullPointerException
  • ClassCastException

compareTo() NullPointerException

In Java, the compareTo() method throws a NullPointerException if either of the objects being compared is null. This ensures that you explicitly handle null values and prevents unexpected behavior.

Example:

Java
public class cmp5   {   // main method   public static void main(String[] args)    {       String str = null;      // null is invoking the compareTo method. Hence, the NullPointerException   // will be raised   int no =  str.compareTo("Geeks");      System.out.println(no);   }   }   

Output:

Exception in thread "main" java.lang.NullPointerException
at cmp5.main(cmp5.java:11)

compareTo() ClassCastException

It is a runtime exception and occurs when two objects of incompatible types are compared in the compareTo() method. 

Example:

Java
public class ClassCastExceptionExample {      public static void main(String[] args) {         Object obj1 = "Hello";         Object obj2 = 10; // Integer object          // Explicitly cast obj2 to String to force the exception         int comparison = ((String) obj2).compareTo(obj1);           System.out.println("Comparison: " + comparison);      } } 

Output:

./ClassCastExceptionExample.java:8: error: incompatible types: Object cannot be converted to String
int comparison = ((String) obj2).compareTo(obj1); // ClassCastException occurs here

Also Read: 

  1. Compare two Strings in Java
  2. Compare two strings lexicographically in Java
  3. Java Integer compareTo() method

Conclusion

compareTo() function in Java is used to compare two strings or objects lexicographically. It returns a positive, zero, or negative integer. In this tutorial, we have covered this method and discussed its working and exceptions.

Read More: Java String Methods



Next Article
Java long compareTo() with examples
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Java
  • Strings
  • Java-Functions
  • Java-lang package
  • Java-Strings
Practice Tags :
  • Java
  • Java-Strings
  • Strings

Similar Reads

  • Short compareTo() method in Java with Examples
    The compareTo() method of Short class is a built in method in Java which is used to compare twoShort objects numerically. Syntax: public int compareTo(Short otherShort) Parameters : This method accepts a mandatory parameter otherShort which is the Short object to be compared. Return type : It return
    2 min read
  • UUID compareTo() Method in Java with Examples
    The compareTo() method of UUID class in Java is used to compare one UUID value with another specified UUID. It returns -1 if this UUID is less than the value, 0 if this UUID is equal to the value, and 1 if this UUID is greater than the value. Syntax: UUID_1.compareTo(UUID_2) Parameters: The method t
    2 min read
  • Path compareTo() method in Java with Examples
    The Java Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a di
    3 min read
  • OffsetTime compareTo() method in Java with examples
    The compareTo() method of OffsetTime class in Java compares this time to another time and returns zero if they are equal or a positive or negative integer depending on the comparison result. Syntax: public int compareTo(OffsetTime other) Parameter: This method accepts a single mandatory parameter ot
    2 min read
  • Java long compareTo() with examples
    The java.lang.Long.compareTo() is a built-in method in java that compares two Long objects numerically. This method returns 0 if this object is equal to the argument object, it returns less than 0 if this object is numerically less than the argument object and a value greater than 0 if this object i
    3 min read
  • ShortBuffer compareTo method in Java with Examples
    The compareTo() method of java.nio.ShortBuffer class is used to compare one buffer to another. Two short buffers are compared by comparing their sequences of remaining elements lexicographically, without regard to the starting position of each sequence within its corresponding buffer. Pairs of short
    4 min read
  • Java String contentEquals() Method with Examples
    contentEquals() method of String class is used to compare the strings. There are two types of contentEquals method available in java.lang.String with different parameters: contentEquals(StringBuffer sb)contentEquals(CharSequence cs)1. contentEquals(StringBuffer sb): contentEquals(StringBuffer sb) me
    3 min read
  • MonthDay compareTo() method in Java with Examples
    The compareTo() method of MonthDay class in Java compares this month-day to another month-day. Syntax: public int compareTo(MonthDay other) Parameter: This method accepts a parameter other which specifies the other month-day to compare to and not null. Returns: The function returns the comparator va
    2 min read
  • TreeSet comparator() Method in Java with Examples
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to co
    3 min read
  • TreeMap comparator() method in Java with Examples
    The comparator() method of java.util.TreeMap class is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys. --> java.util Package --> TreeMap Class --> comparator() Method Syntax: public Comparator comparator() Return Ty
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences