When should we use Primitive or Wrapper types in Java?

One good thing about Java is it supports primitive data types as it has some added advantages.

List of primitive types in Java:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

List of primitive type wrapper classes in Java:

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Char
  • Boolean

One of the most famous interview questions is "When should you use Primitive types and when its Wrapper types?"

To answer this is a single line -

We must use primitive types when memory efficiency, performance, and default values are crucial; and prefer wrapper classes when dealing with nullability or using Java Collections.


How primitives in Java are memory efficiency?


How primitives in Java are more performance efficient?

It is also important to note that primitives are auto-assigned to default value by the Java JVM, whereas primitives are assigned a null value.

public class Main {

    static int i1;
    static float f1;

    static Integer i2;
    static Float f2;

    public static void main(String[] args) {

        System.out.println(i1);
        System.out.println(i2);

        System.out.println(f1);
        System.out.println(f2);

    }
}



0
null

0.0
null



Below are some more points that one must keep in mind while choosing between primitive types and its wrapper.