Introduction to JVM Languages
上QQ阅读APP看书,第一时间看更新

References and null references

Let's take a look at the following code:

    Product p = new Product();
p.setName("Box of biscuits");

Assume that Product is a class here that is available to the program. We create a Product instance and the p variable points to it. We then call the setName method on this object instance.

JVM does not give direct access to the memory location where the Product object is stored. It just provides a reference to the created object. When using the variable p, JVM figures out which memory location it has to reach for the object that the variable points to.

We add the following lines to the previous snippet:

    p = null;
p.setName("This line will produce an error at run-time");

A reference can be cleared explicitly by assigning null to it. Note that this is not necessary for variables declared inside a method, as they will be cleared automatically upon exiting the method. However, it is perfectly acceptable to still do it anyway. Now the variable p is a null reference. In the next paragraph, we will see what will happen to object instances that are no longer referenced by any reference type variable.

The preceding code will compile fine. When running the program, the last line will cause a NullPointerException error, though. If no error handling capability was implemented in the application, it will crash. Many modern IDEs try to detect these situations and warn the developer about them.