I quote from Herbert Schildt Chapter 3 Data types, Variables and Arrays :
The primitive types represent single values not complex objects. Although Java is otherwise completely object-oriented, the primitive types are not. The reason for this efficiency. Making the primitive types would have degraded performance too much.
The primitive types are defined to have an explicit range and mathematical behavior. Languages such as C, C++ allow the size of an integer to vary based upon the dictates of the execution environment. However, Java is different. Because of Java’s portability requirement, all data types have a strongly defined range. For example, an int is always 32-bit regardless of the particular platform. This allows programs to be written that are guaranteed to run without porting on any machine architecture. While strictly specifying the size of an integer may cause a small loss of performance in some environments, it is necessary in order to achieve portability.
What does he mean by the last 2 lines ? And how come specifying the size of an integer may cause a small loss of performance in some environments?
Primitive data types - includes byte , short , int , long , float , double , boolean and char.
Primitive data types specify the size and type of variable values. They are the building blocks of data manipulation and cannot be further divided into simpler data types. There are 8 types of Primitive data types in Java – Boolean, char, byte, int, short, long, float, and double.
There are 8 primitive types of data built into the Java language. These include: int, byte, short, long, float, double, boolean, and char.
In "lower" languages, primitive data types sizes are often derived from the CPU's ability to handle them.
E.g., in c, an int
is defined as being "at least 16 bits in size", but its size may vary between architectures in order to assure that "The type int should be the integer type that the target processor is most efficient working with." (source). This means that if your code makes careless assumptions about an int
's size, it may very well break if you port it from 32-bit x86 to 64-bit powerpc.
java, as noted above, is different. An int
, e.g., will always be 32 bits. This means you don't have to worry about its size changing when you run the same code on a different architecture. The tradeoff, as also mentioned above, is performance - on any architecture that doesn't natively handle 32 bit calculations, these int
s need to be expanded to the native size the CPU can handle (which will have a small penalty), or worse, if the CPU can only handle smaller int
s, every operation on an int
may require several CPU operations.
A few (very few) computers use 36 bit architecture, so you need an extra step to mask off bits, simulate overflows, etc.
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