When to use primitive and when reference types in Java?

We always should use primitives (such as boolean, int, etc). When the primitive types are not able to handle our needs then we should use the wrapper class of that primitive.

Where we can’t use primitive?

Java generics do not support primitive types. It only supports the wrapper class of those primitive types. So we must use wrapper class such as Boolean, Integer for java generics.

The code

List primitiveList = new ArrayList();  // This is not allowed.
List primitiveWrapperList = new ArrayList();   // This is fine.

How to do autoboxing?

In java, we can take advantage of autoboxing very easily. It does it automatically. Check the following code:

// Autoboxing will turn 20, 30, 40 into Integer from int.
List numbers = Arrays.asList(20, 30, 40); 

How to do unboxing?

In java, we can take advantage of unboxing very easily. It does it automatically. Check the following code:

List marks = Arrays.asList(20, 30, 40); 
int sum = 0;

// Integer from the "marks" List is unboxed into int.
for (int number : marks) {
  sum += number;
}
Share