. operator
Example:
Object obj = new Object();
String text = obj.toString(); // 'obj' is dereferenced.
Dereferencing follows the memory address stored in a reference to the place in memory where the actual object resides.
When an object is found, the requested method (e.g., toString
in this case) is called.
When a reference has the value null
, dereferencing results in a NullPointerException
:
Object obj = null;
obj.toString(); // Throws a NullpointerException when this statement is executed.
null
indicates the absence of a value, meaning that following the memory address leads nowhere. Therefore, there is no object on which the requested method can be called.Example:
Object obj = new Object(); // Note the 'new' keyword
Explanation:
Object
is a reference type.obj
is the variable in which to store the new reference.Object()
is the call to a constructor of Object
.What happens:
Object()
is called to initialize that memory space.obj
, so that it references the newly created object.Contrast with primitives:
This process is different from primitives, where the actual value is stored in the variable:
int i = 10;
10
is stored in i
.