How is reference to java object is implemented?

前端 未结 5 1557
刺人心
刺人心 2020-12-07 02:40

Is pointer is just used for implementing java reference variable or how it is really implemented? Below are the lines from Java language specification

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 03:39

    A primitive type is always passed by value. where as a Class Variable is actually a reference variable for the Object.

    Consider a primitive type:

    int i=0; 
    

    now the value of this primitive type is stored in a memory location of address 2068. Every time you use this primitive type as a parameter, a new copy is created as it is not pass by reference but pass by value.

    Now consider a class variable:

    MyClass C1 = new MyClass();
    

    Now this creates an object of the class type MyClass with a variable name C1.

    The class variable C1 contains an address of the memory location of the object which is linked to the Valriable C1. So basically the class variable C1 points to the object location(new MyClass()).

    And primitive types are stored in stack and objects in heaps.

提交回复
热议问题