String values in Kotlin

  • A+

In Java, if we do new String() we know it would create new string object and it would be different from the object created without 'new'(even if contents are same).

//Java     System.out.println("First" == new String("First")); // false always 

In Kotlin, if I try to create String even by creating StringBuilder, it would still be identical to that created without String(..).

//Kotlin println("First" == String(StringBuilder("First"))) //true always 

If the created String(StringBuilder(..)) is going to reuse same string value, why give constructor? Does it do any value add, looking for such use-case.



By using the == operator you're checking structural equality between the strings (whether they represent the same sequence of characters). The Java equivalent of your Kotlin comparison code above would be something like this:

Object.equals("First", new String(new StringBuilder("First"))); // true 

To check reference equality in Kotlin, you need to use the === operator.

Check out the Kotlin reference on Equality.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: