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.
val string1 = "Educative"val string2 = "educative"val areTheyEqual = string1==string2// Driver Codeprintln(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.
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.
val string1 = "Educative"val string2 = "educative"var areTheyEqual = string1.toUpperCase==string2.toUpperCaseprintln(areTheyEqual) // Driver CodeareTheyEqual = string1.toLowerCase==string2.toLowerCaseprintln(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 ofval
to declare the variableareTheyEqual
. This is because we needed to reassign it a new value.
In the next lesson, we will learn how to create multiline strings.