Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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" is a reference, and it is dereferenced when used to access the Integer object it refers to:

    Integer ref = new Integer(7);     
    // Dereference "ref" to access the object it refers to.
    System.out.println(ref.toString()); 

And NullPointerExceptions occur when that dereferencing process fails:

Integer ref = null;
// Dereferencing "ref" causes an exception.
System.out.println(ref.toString()); 

However, my interpretation conflicts with one of the topics being tested on Oracle's new Java SE 8 Programmer I exam (beta):

Explain an Object's Lifecycle (creation, "dereference by reassignment" and garbage collection)

So according to whoever created the Java 8 exam, dereferencing in Java is the act of reassigning a reference, rather than the act of evaluating a reference:

For example:

    // Create an Integer object, and a reference to it.
    Integer ref = new Integer(7); 
    ref = null; 
    // Now (according to Oracle?):
    // - The reassignment means ref has been "dereferenced".
    // - The dereferenced object is now eligible for Garbage Collection.

Googling the issue anecdotally suggests that Oracle's definition is more widely used, but that doesn't mean it is correct, and the only hit on google for "dereference by reassignment" is for that new Java 8 exam! The JLS doesn't really shed any light either way.

Is there any formal or authoritative definition (as opposed to personal opinions) on what dereferencing really means in Java? (i.e. Does it relate to evaluation or reassignment?)

It seems strange that two completely different definitions manage to coexist.

like image 921
skomisa Avatar asked Sep 06 '25 03:09

skomisa


1 Answers

Although there is no official definition, the word 'dereference' is used in some of the Java error statements.

For example, if you write following code:

char ch = 'A';
if (ch.isLetter()) { }

You get error: char cannot be dereferenced

So, one can say that accessing the state or behaviour of an object using its reference with the help of the . operator is dereferencing.

like image 72
Yogesh Umesh Vaity Avatar answered Sep 07 '25 23:09

Yogesh Umesh Vaity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!