Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer as primitive type

Tags:

java

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?

like image 601
user241924 Avatar asked Jan 20 '10 05:01

user241924


2 Answers

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)

like image 69
maxpolk Avatar answered Nov 10 '22 17:11

maxpolk


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.

like image 33
x4u Avatar answered Nov 10 '22 16:11

x4u