Equality Operators (==, !=) and Referential equality Operators (===, !==) in Kotlin

Definition

  • The equality operators are operators that check if the values that are compared are equal. This is similar to the Java equals() method. The equality operators are "==" and "!="
  • The referential equality operators are operators that check if the values and the object of the variables that are compared are equal. The referential equality operators are "===" and "!=="

Syntax

1. Equality Operators

if(value1 == value2){
	//Block of Code
}
(OR)
if(value1 != value2){
	//Block of Code
}

For example,

var num1 = 5
var num2 = 5
if(num1 == num2){
	//Block of Code
}

2. Referential Equality Operators

//value1 and value2 are of different Object types
if(value1 === value2){
	//Block of Code
}
(OR)
if(value1 !== value2){
	//Block of Code
}

For example,

var num1 : Any = 5
var num2 = 5
if(num1 === num2){
	//Block of Code
}

Equality and Referential Equality Operator Example Program in Kotlin

//Equality and Referential Equality Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    var num1 : Any  = 100.2
    var num2 = 100.2
    var num3 = 100
    var num4 : Int = 100

    //Checking Equality of same value and non-mentioned Object type
    if(num1 == num2){
        println("$num1('Any' Data type) and $num2(Inferred Data Type) are equal using Equality Operator")
    }

    //Checking Non-Equality of different values and non-mentioned Object type
    if(num1 != num3){
        println("$num1('Any' Data type) and $num3(Inferred Data Type) are not equal using Non-Equality Operator")
    }

    //Checking Referential Equality of same value and non-mentioned Object type
    if(num3 === num4){
        println("$num3(Inferred Data Type) and $num4('Int' Data Type) are equal using Referential Equality Operator")
    }

    //Checking Referential Non-Equality of same value with boxed Object
    if(num1 !== num2){
        println("$num1('Any' Data Type) and $num2(Inferred Data Type) are not equal using Referential Non-Equality Operator")
    }
}

Sample Output

100.2('Any' Data type) and 100.2(Inferred Data Type) are equal using Equality Operator
100.2('Any' Data type) and 100(Inferred Data Type) are not equal using Non-Equality Operator
100(Inferred Data Type) and 100('Int' Data Type) are equal using Referential Equality Operator
100.2('Any' Data Type) and 100.2(Inferred Data Type) are not equal using Referential Non-Equality Operator