Boxing of number giving true for number less than 128

val boxedA: Int? = 127
val anotherBoxedA: Int? = 127
println(boxedA === anotherBoxedA)      // Output true

val boxedB: Int? = 127
val anotherBoxedB: Int? = 127
println(boxedB === anotherBoxedB)    // Output false

I think the compiler is free to use the same object for boxing when it feels like. And I believe a few ints, I guess up to 127 are all boxed once at startup just in case.

Is there a specific question you have about this behavior?

1 Like

Yes, as mentioned in kotlin docs, by default all elements are boxed, so they will be different reference for every object, which means whatever the value its shouldn’t be equal

Yes, as mentioned in kotlin docs, by default all elements are boxed

Where exactly did you read that?

On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int? ) or generics are involved. In the latter cases numbers are boxed.

Java specification states that numbers from -128 to 127 are always boxed to the same object.

All example variables are nullable so they will be boxed and if they are in range from -128 to 127, they will always point to the same object when using Kotlin on JVM.


I think for range -128 to 127 by default use Int cache

1 Like

Boxing an Int in an object does not mean that a new object is used each time. Indeed, on the jvm all integer literals up to 128 use the same object when boxed. A practice known as interning.

1 Like