0

Objects are reference type, which means reference type of an object holds the address in memory where actual data is stored.

For example

Integer object = new Integer(3);

But if we talk about primitive types, like int number = 3; then where number is pointing to ?

Is it itself in memory ? What it holds ?

Jenny Rose
  • 111
  • 9

3 Answers3

2

In java we have something called stack memory where all the primitive are stored.

There was a similar discussion which you can visit by following this link

Where does the JVM store primitive variables?

0

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.

Rachayita Giri
  • 487
  • 5
  • 17
  • *"But if you pass the Integer object, it is passed by reference... "* ... more accurately, the reference itself is passed by value to a method. Therefore, reassigning a new object reference to the argument variable in the method will have no effect on the reference variable in the calling code. – scottb Oct 22 '19 at 20:52
0

Primitive type can be stored in both stack and heap depending on its scope.

In your example given above, numberis just a chunk of memory holding binary value representation of number 3, depending if it is a local variable or an instance variable, it can be stored in either stack or heap.

See the post Do Java primitives go on the Stack or the Heap? and Stack Memory and Heap Space in Java

class Person {
    int pid;
    String name;

    // constructor, setters/getters
}

public class Driver {
    public static void main(String[] args) {
        int id = 23;
        String pName = "Jon";
        Person p = null;
        p = new Person(id, pName); // primitive in heap
    }
}

Example of primitive type in heap: When p is assigned with Person constructor, a new instance of Person class is created in heap memory, which has a memory chunk holding value of 23.

hydroPenguin
  • 66
  • 1
  • 4