Video in progress
What is the difference between a primitive type and a reference type in Java?
A primitive variable stores the value itself (int x = 5), while a reference variable stores a reference to an object on the heap. A primitive can't be null, but a reference can.
📖 Answer
Java has 8 primitive types: byte, short, int, long, float, double, char, boolean. Everything else is a reference type: String, arrays, your own classes, and Integer too.
int a = 10;
int b = a; // the value was copied
b = 20; // a is still 10
int[] x = {1, 2};
int[] y = x; // the reference was copied: both point to the same array
y[0] = 99; // x[0] is 99 too
In practice the difference shows up here:
- a primitive has a default value (as a field:
0,false), while a reference field defaults tonull; - primitives can't be used in generics:
List<Integer>, notList<int>; - working with primitives is faster and takes less memory: between an
int[]and aList<Integer>with a million elements, the difference is several times over.
Sign up to mark studied questions and save your progress.