ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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!
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.