Why Do Programmers Still Use Primitive Types in Java?
Despite the introduction of boxing and unboxing in Java 5, many developers continue to utilize primitive types like int over their object counterparts, such as java.lang.Integer. This practice begs the question of why this happens, given the added convenience offered by object types.
As outlined in Joshua Bloch's "Effective Java" (Item 5: "Avoid creating unnecessary objects"), the use of primitives can yield significant performance benefits. In his code example, summing longs using a Long object takes 43 seconds, while using primitives accelerates the process to 6.8 seconds.
Another factor contributing to the use of primitives is the lack of native value equality in object types. To determine equality, the verbose equals() method must be employed, unlike the efficient == operator available for primitives.
Consider the following code snippet:
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 } }
The output reveals the inconsistency in value equality between new Integer() and Integer.valueOf(). While the Java Language Specification (JLS) requires a cache of at least 256 integer flyweights ([-128; 127]), JVM implementers may extend this range. This means that certain values may be cached on some systems but not others, leading to unexpected behavior.
The above is the detailed content of Why Do Java Programmers Favor Primitive Types Despite the Existence of Wrapper Classes?. For more information, please follow other related articles on the PHP Chinese website!