Sobes.tech
Junior — Middle

What is the difference between comparing objects with the == operator in Java and Kotlin?

sobes.tech AI

Answer from AI

In Java, the operator == compares object references, meaning it checks whether two variables point to the same object in memory.

In Kotlin, the operator == compares the values of objects by calling the equals() method, thus checking for logical equality of the objects' contents.

If you need to compare references in Kotlin, the operator === is used.

Example:

val a = String("test")
val b = String("test")

println(a == b)  // true, value comparison
println(a === b) // false, different objects

In Java:

String a = new String("test");
String b = new String("test");

System.out.println(a == b);      // false, different objects
System.out.println(a.equals(b)); // true, value comparison