How to compare two strings using equals() method in Scala? String equals() Method

Here, we will learn about equals() method in Scala. The equals() method compares two strings and returns a Boolean value based on the comparison.
Submitted by Shivang Yadav, on January 29, 2021

String is an immutable collection that stores sequences of characters.

How to compare two strings?

We can compare two strings in Scala using the equals() method defined on the string.

String equals() Method

The equals() method in Scala is used to compare the given strings and return a Boolean value based on the comparison. The strings can be string or any other object.

Syntax:

stringObj1.equals(stringObj2)

Parameters: The method accepts a single parameter which is a string or object which is to be compared with.

Return Value: It returns a Boolean value based on the comparison of the strings.

Example 1: Compare two strings in Scala

object myObject {
    def main(args: Array[String]) {
        val string1 = "Scala"
        println("The strings are '" + string1 + "' , 'scala'")
    
        val isEqual = string1.equals("scala")
    
        if(isEqual)
            println("The strings are equal!")
        else 
            println("The strings are not equal!")
    }
}

Output:

The strings are 'Scala' , 'scala'
The strings are not equal!

Example 2: Compare two string objects in Scala

object myObject {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "Scala"
    
        println("The strings are '" + string1 + "' , '" + string2 + "'" )
    
        val isEqual = string1.equals(string2)
    
        if(isEqual)
            println("The strings are equal!")
        else 
            println("The strings are not equal!")
    }
}

Output:

The strings are 'Scala' , 'Scala'
The strings are equal!



Comments and Discussions!

Load comments ↻






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