Testing String Equality

In the following lesson, you will learn how to compare strings in Scala.

We'll cover the following

Problem

We want to compare two strings to check whether they are equal. When strings are equal, it simply means that both strings are composed of the same characters in the same order, i.e., they are identical.

Solution

In Scala, you use the == method to test the equality of two objects. The result will either be true or false depending on whether the objects are equal or not.

Let’s look at an example.

Press + to interact
val string1 = "Educative"
val string2 = "educative"
val areTheyEqual = string1==string2
// Driver Code
println(areTheyEqual)

In the example above, the first character of both strings is different; string1 has an uppercase E while string2 has a lowercase e. This means the two strings are not equal and hence, our output is false.

We can also look at an example where both strings are equal, and just to make things different, let’s not create a new bool variable, rather, we will directly compare the strings in the println method.

Press + to interact
val string1 = "Hakuna Matata"
val string2 = "Hakuna Matata"
println(string1==string2)

Looking at our first example, what if we didn’t care about letter cases and only wanted to check if the same letters, regardless of if they are uppercase or lowercase, exist in both strings.

One way to ensure that our code is not case-sensitive is by making the characters of both strings either upper case or lower case. Scala has in-built methods that can help you do just that; toUpperCase and toLowerCase.

Let’s look at them in action.

Press + to interact
val string1 = "Educative"
val string2 = "educative"
var areTheyEqual = string1.toUpperCase==string2.toUpperCase
println(areTheyEqual) // Driver Code
areTheyEqual = string1.toLowerCase==string2.toLowerCase
println(areTheyEqual) // Driver Code

In the code above, string1.toUpperCase converts the characters of string1 to upper case and string1.toLowerCase converts the characters of string1 to lower case; the same goes for string2. == now compares the new uppercase strings and the new lowercase strings and the output in both cases is true.

Note how we used var instead of val to declare the variable areTheyEqual. This is because we needed to reassign it a new value.


In the next lesson, we will learn how to create multiline strings.