2
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

val b: Int = 10000
val boxedB: Int? = b
val anotherBoxedB: Int? = b

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false

What I don't understand is what is the difference between boexA === andotherBoxedA and boexB === andotherBoxedB

and more confusion is when change b t0 100 the output is true true

val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

val b: Int = 100
val boxedB: Int? = b
val anotherBoxedB: Int? = b

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // true

so, please I need explanation for this code.

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
  • 5
    It's probably the small cache of integers maintained by the runtime. See https://stackoverflow.com/questions/15052216/how-large-is-the-integer-cache for more details. – omajid Jun 21 '20 at 18:23
  • Yes, thank you very much @MattTimmermans omajid – Ashraf Mohamed Jun 21 '20 at 18:52

1 Answers1

7

So, as an optimization Integer values in -128 to 127 range get cached and any other object hold similar value to a cached one it will get a reference of the cached value (similar to string pool) so when val a:Int = 100 and then val boxedA :Int? = a, so what happened here is an Integer object got created with the value 100, so when val anotherBoxedA :Int? = a, the something an object got created, but wait, if it will hold the same value which is 100 and the value is in range -128 to 127 so anotherBoxedA will get the same reference as boxedA so when boxedA === anotherBoxedA will produce true

on the other hand b=10000 which is larger than the cache range (-128 : 127) so boxedB = b will create a new Integer object , anotherBoxedB = b will again create a new object , so (boxedB === anotherBoxedB) will produce false