Is there a formal or authoritative definition for “dereferencing” in Java?

后端 未结 2 1248
深忆病人
深忆病人 2020-12-16 11:56

Coming from a C and C++ background, I have always assumed that dereferencing in Java is the process of accessing an object via its reference.

For example, \"ref\" i

2条回答
  •  执念已碎
    2020-12-16 12:21

    Java variables are either "primitive types" or "reference types" in Oracle's terminology (well, other than the special type of null). I came to Java from a C++ background and always found it easiest to think of reference types like pointers as that makes it easiest to understand how they work (though there are important differences), however because all non-primitive variables are like that there's no concept of evaluation (no equivalent of C++'s dereferencing of pointers).

    So, in your example:

    Integer ref = new Integer(7); 
    ref = null;
    

    On the first line an object is created on the heap and ref refers to it. On the second line ref is changed to refer to null. There are no more references to the object on the heap so it will have become eligible for garbage collection, but until such time as the garbage collector does so it will actually still be there (excluding any clever JVM optimisation of this simple example!).

    AFAIK there isn't an official definition of "dereferencing" in Java. Because there isn't the distinction between evaluation and assignment it does make sense, though it's not a term that I think is widely used.

提交回复
热议问题