Primitive data types are stored in the stack, while reference data types are stored in the heap.
So when you say int number=3;
, a 32-bit long (by default) chunk of memory on the stack is put aside. This chunk holds the value 3 and can be identified by the variable name number.
But when you say Integer object = new Integer(3);
, the memory is assigned from the heap, and a reference is created to that chunk of memory. This memory is for the object
instance of the Integer
class, so it gets more memory than your int number
. This is because the Integer
class wraps inside it, not just a primitive int but also some other methods that can be used on its instances.
You should also understand that when you pass a primitive data type to an assignment statement or to a function, it is passed by copy so the changes don't reflect on the original variable. But if you pass the Integer object, it is passed by reference, i.e. a pointer to that large chunk of memory on the heap, so the changes are visible on the actual object.