Skip to content
Related Articles

Related Articles

Scala String compareTo() method with example
  • Last Updated : 03 Oct, 2019

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:




// 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)
      
    }
Output:
0

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






// 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)
      
    }
Output:
1

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




// 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)
      
    }
Output:
-32

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :