×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String compareTo() Method

By IncludeHelp Last updated : October 21, 2024

Description and Usage

The compareTo() method in Scala is used to compare two strings in Scala and return an integer value denoting the difference.

The value of comparison is determined as:

  • 0, if both strings are the same.
  • x, if string1 is greater than string2. The value of x is denoted by the difference of value of characters.
  • -x, if string1 is smaller than string2. The value of x is denoted by the difference of value of characters.

Syntax

string1.compareTo(string2)

Parameters

The method accepts a single parameter which is the string to be compared.

Return Value

It returns an integer value which denotes the result of difference between the strings.

Example 1: When both strings are the same

object MyClass {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "Scala"
        
        println("String1 = " + string1)
        println("String2 = " + string2)
        
        val compStr = string1.compareTo(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = Scala
String2 = Scala
Value of comparison between 'Scala' and 'Scala' is 0

Example 2: When both strings are not same

object MyClass {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "programming"
    
        println("String1 = " + string1)
        println("String2 = " + string2)
    
        val compStr = string1.compareTo(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = Scala
String2 = programming
Value of comparison between 'Scala' and 'programming' is -29

Example 3: When both strings are not the same

object MyClass {
    def main(args: Array[String]) {
        val string1 = "scala"
        val string2 = "Scala"
        
        println("String1 = " + string1)
        println("String2 = " + string2)
        
        val compStr = string1.compareTo(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = scala
String2 = Scala
Value of comparison between 'scala' and 'Scala' is 32

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.