Search code examples
javaprimitive-typesreference-type

Is it a better practice to use Reference types or primitive types in Java?


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


Solution

  • 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.