Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I never use primitive types again?

Tags:

java

types

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?

like image 710
Hans Sjunnesson Avatar asked Sep 23 '08 21:09

Hans Sjunnesson


People also ask

Should I use primitive or wrapper?

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.

Why Java still use primitive types?

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.

When should you use primitives?

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.

Why we use non primitive data types?

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.


1 Answers

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.

like image 65
Michael Deardeuff Avatar answered Sep 20 '22 12:09

Michael Deardeuff