Despite the introduction of boxing and unboxing in Java 5, developers continue to employ primitive types in their code. This might seem counterintuitive given the added convenience that boxed types offer, but there are several tangible benefits to using primitives.
Performance Considerations
Joshua Bloch's "Effective Java" highlights the potential performance impact of using Long instead of long in a simple calculation. Boxing and unboxing operations involve allocating and deallocating objects, which can slow down code execution. As demonstrated in the example provided, using primitive types can significantly reduce runtime.
Value Equality
Another advantage of primitive types is their native notion of value equality. The == operator compares the values directly, while the .equals() method on boxed types requires extra steps and overhead. This can lead to more concise and efficient code, particularly in performance-critical scenarios.
Caching Implications
In Java, small integer values ([-128; 127]) are cached by the JVM. This means that the exact same object is returned for these values, which can improve performance compared to using boxed types. However, for values outside this range, new objects are created, potentially introducing unnecessary object overhead.
Example: The "Biziclop" Puzzle
The behavior of .equals() for boxed integers can be confusing. Consider the following code:
class Biziclop { public static void main(String[] args) { System.out.println(new Integer(5) == new Integer(5)); // false System.out.println(new Integer(500) == new Integer(500)); // false System.out.println(Integer.valueOf(5) == Integer.valueOf(5)); // true System.out.println(Integer.valueOf(500) == Integer.valueOf(500)); // false } }
Why does line (3) return true and line (4) return false? The answer lies in the caching mechanism. The values 5 and -5 are cached by the JVM, so two instances of new Integer(5) refer to the same object. However, 500 is not cached, so two instances of new Integer(500) are distinct objects. Integer.valueOf(), on the other hand, uses an additional cache that includes all integers, ensuring that for values within this cache (typically all integers in the range [-128; 127]), the same object is returned.
The above is the detailed content of Why Do Java Developers Prefer Primitive Types Over Wrapper Classes?. For more information, please follow other related articles on the PHP Chinese website!