0

Is it considered a better practice to use and manipulate Reference types instead of primitive types in Java ?

We often see java programs mixing both of them, is it better to use only primitive types or only reference types ? Or mix them according to the needs and what are the criteria to choose between a primitive or reference type ?

Thanks

JavaDev
  • 307
  • 1
  • 3
  • 16
  • If you consider the existance of auto-boxing mechanism I guess there's no difference (in "better/worse" context). Just keep in mind that reference types can be `null`. – Crozin Jul 28 '16 at 09:47
  • 4
    @Crozin no difference, unless you're doing math in a loop. Then big difference. – Andy Turner Jul 28 '16 at 09:48
  • 2
    @Crozin - Operations on primitives are usually faster than their corresponding wrappers – TheLostMind Jul 28 '16 at 09:49
  • 1
    Reference types can be used as generic types. Reference types can be null. Reference types need to be compared with `.equals()` instead of `==`. Depends what your requirements are. – khelwood Jul 28 '16 at 09:52
  • @AndyTurner can you explain the difference in terms of performance ? – JavaDev Jul 28 '16 at 10:13
  • @JavaDev read *Effective Java 2nd Ed* Item 49 "Prefer primitive types to boxed primitives". – Andy Turner Jul 28 '16 at 10:41

2 Answers2

2

Assuming you mean primitive wrapper types (Integer, Boolean, etc.) and not reference types in general: when you have a choice (often you don't: e.g. you are using API which requires one or the other, or you use them as generic type arguments, or you want to be nullable), prefer primitive types, because on the whole this will make your code simpler and faster.

Be careful if you need to switch from one to another, because == will still compile but give different results... usually.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
1

One important criteria is the question: Can it be null? For example think of an id in an database-entity and ask yourself if there is a time where the id can be null.

You can choose primitive type for non-null-Values.

Tobias Otto
  • 1,634
  • 13
  • 20