Why there is primitive type for integer(int) even though we have an object for integer as Integer? But the same is not with String type. There is no such primitive type for String. Always String deals with object reference?
Speed. It's much faster for machine code to add two int's using native CPU instructions, rather than having to take two Integer objects, extract the int values from them, then add those, creating a new result Integer object to contain the result. (how JNI maps primitives)
Strings are complex, have many methods, and as such have no machine code counterpoint. They are promoted to a true Object. Also, a String shares state with other Strings created with the same value. No primitive value shares state with other primitive values like this. (immutable can be shared | primitive no sharing)
This is because processors (CPUs) have direct support for integer types but not for strings. And for performace reasons Java supports some native types that are likely to be supported by the processors the JVM might run on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With