Kotlin Program to Compare Strings

Example 1: Compare two strings

fun main(args: Array<String>) {

    val style = "Bold"
    val style2 = "Bold"

    if (style == style2)
        println("Equal")
    else
        println("Not Equal")
}

When you run the program, the output will be:

Equal

In the above program, we've two strings style and style2. We simply use equality operator (==) to compare the two strings, which compares the value Bold to Bold and prints Equal.


Example 2: Compare two strings using equals()

fun main(args: Array<String>) {

    val style = "Bold"
    val style2 = "Bold"

    if (style.equals(style2))
        println("Equal")
    else
        println("Not Equal")
}

When you run the program, the output will be:

Equal

In the above program, we have two strings style and style2 both containing the same world Bold.

As you can see we've used equals() method to compare the strings. Like Example 1, it compares the value Bold to Bold.


Example 3: Compare two strings using === (Doesn't work)

fun main(args: Array<String>) {

    val style = buildString { "Bold" }
    val style2 = buildString { "Bold" }

    if (style === style2)
        println("Equal")
    else
        println("Not Equal")
}

When you run the program, the output will be:

Not Equal

In the above program, instead of creating a string using just quotes, we've used a helper method buildString to create a String object.

Instead of using == operator, we've used === (referential equality operator) to compare the strings. This operator compares whether style and style2 are essentially the same object or not.

Since, they are not, Not Equal is printed on the screen.


Example 4: Different ways to compare two strings

Here are the string comparison which are possible in Java.

fun main(args: Array<String>) {

    val style = buildString { "Bold" }
    val style2 = buildString { "Bold" }

    var result = style.equals("Bold") // true
    println(result)

    result = style2 === "Bold" // false
    println(result)

    result = style === style2 // false
    println(result)

    result = "Bold" === "Bold" // true
    println(result)
}

When you run the program, the output will be:

true
false
false
true

Here's the equivalent Java code: Java Program to compare strings.

Did you find this article helpful?