Scala String compareTo() method with example

The compareTo() method is utilized to compare a string with another string.
Some points to remember:

  • Here, If a string(S1) is same as string(S2) in comparison then this method returns zero.
  • If S1 is less than S2 then a negative number is returned which is the difference of character value.
  • If S1 is greater than S2 then a positive number is returned.

Method Definition: int compareTo(String another String)
Return Type: It returns an integer.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of compareTo()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
        // Creating a String
        val m1 = "Nidhi"
          
        // Applying compareTo() method
        val result = m1.compareTo("Nidhi")
          
        // Displays output
        println(result)
      
    }

chevron_right


Output:

0

It returns zero as both the strings are same.
Example #2:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of compareTo()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
        // Creating a String
        val m1 = "Nidhi"
          
        // Applying compareTo() method
        val result = m1.compareTo("Nidh")
          
        // Displays output
        println(result)
      
    }

chevron_right


Output:

1

It returns a positive number as S1 is greater than S2 here.
Example #3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of compareTo()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
        // Creating a String
        val m1 = "Nidhi"
          
        // Applying compareTo() method
        val result = m1.compareTo("nidh")
          
        // Displays output
        println(result)
      
    }

chevron_right


Output:

-32

It returns a negative number as S1 is less than S2 here.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.