When to use wrapper class and primitive type

Viewed 88885

When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?

11 Answers

Primitive values in Java are not object. In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.

All Wrapper classes are final. The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.

Although, the void class is considered a wrapper class but it does not wrap any primitive values and is not initiable. It does not have public constructor, it just denotes a class object representing the keyword void.

When to Use Primitive Types

  • When doing a large amount of calculations, primitive types are always faster — they have much less overhead.
  • When you don’t want the variable to be able to be null.
  • When you don’t want the default value to be null.
  • If the method must return a value

When to Use Wrapper Class

  • When you are using Collections or Generics — it is required
  • If you want the MIN_SIZE or MAX_SIZE of a type.
  • When you want the variable to be able to be null.
  • When you want to default value to be null.
  • If sometimes the method can return a null value.

from https://medium.com/@bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9

Related