Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:
int i = 4;
...
if (i == 10)
doStuff();
Later on you figure that you want the variable i to be either defined or undefined, so you change the above instantiation to:
Integer i = null;
Now the equality check fails.
Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?
Verdict. Generally, choose primitive types over wrapper classes unless using a wrapper class is necessary. Primitive Types will never be slower than Wrapper Objects, however Wrapper Objects have the advantage of being able to be null.
As we've seen, the primitive types are much faster and require much less memory. Therefore, we might want to prefer using them. On the other hand, current Java language specification doesn't allow usage of primitive types in the parametrized types (generics), in the Java collections or the Reflection API.
Object version of primitives are used if you want to express that the value can be null. A primitive is always initialized to zero and thus can never be null. In a RESTful web service java classes are used to model the service request and responses.
Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitive types can be null . A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
Using the boxed types does have both performance and memory issues.
When doing comparisons (eg (i == 10)
), java has to unbox the type before doing the comparison. Even using i.equals(TEN)
uses a method call, which is costlier and (IMO) uglier than the == syntax.
Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself.
A sneaky gotcha? i.equals(j)
when i is null
.
I always use the primitives, except when it may be null
, but always check for null
before comparison in those cases.
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