0

there

I'm following the Kotlin tutorial on the offical site, and quite confusing about the result in the example as below :

fun main() {
    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a

    val b: Int = -129
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b

    val c: Int = -128
    val boxedC: Int? = c
    val anotherBoxedC: Int? = c

    val d: Int = 127
    val boxedD: Int? = d
    val anotherBoxedD: Int? = d
    
    val e: Int = 128
    val boxedE: Int? = e
    val anotherBoxedE: Int? = e
    
    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // false
    println(boxedC === anotherBoxedC) // true
    println(boxedD === anotherBoxedD) // true
    println(boxedE === anotherBoxedE) // false
}

Would anyone help provide an explaination why Int class seems to hava a different storage method for data range [-128, 127) ?

I can not find any clues from the Integer class definition.

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

Thanks in advance.

whisper
  • 95
  • 1
  • 6
  • 1
    One source is the mentioned answer (which references the ultimate source of truth, the Java Language Specification), the other source is the [`Integer.valueOf(int)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Integer.html#valueOf(int)) documentation: _This method will always cache values in the range -128 to 127, inclusive_ – Thomas Kläger Mar 24 '22 at 06:25

1 Answers1

1

Int by default caches values from [-128,127]. You can look at the following link for more information https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)

Abhishek
  • 26
  • 3