Open In App

Scala String compareTo() method with example

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

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.


Article Tags :