A primitive type variable holds the value itself, while a reference type variable holds a reference that points to an object. Java has eight primitives:
- Integer types:
byte,short,int,long - Floating-point types:
float,double booleanfortrueorfalse, andcharfor a single character
Each primitive has a fixed size and can never be null.
Classes, interfaces and arrays are reference types, and so are enums. Their objects are always allocated on the heap. Assigning one reference variable to another copies the reference, not the object, so both variables then point to the same object.
Where a primitive lives depends on where it is declared. A local int sits in the method's stack frame, but an int field sits inside its object on the heap.
int x = 10; // primitive - stores value 10
String str = "Hello"; // reference - stores memory address of String object
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓