Java Reference
In-Depth Information
Note You might have tried to execute this code snippet to see something
like the following appearing on‐screen:
Now, book equals: null
And now, book equals: Book@709fa12f
What's going on with this Book@709fa12f (your output will differ and return
a different part after the @ )? The reason for this is that all Java objects have
a built‐in method to return their so‐called “String representation,” which can
be extended by programmers to provide a friendly output for an object, that
is, a String that textually represents the object (don't worry about the specif-
ics of this too much for now; you will get back to this later). The key aspect to
know here is that, when no extension is provided by the programmer, Java will
just resort to showing the class name ( Book ), followed by an @ , followed by the
hexadecimal representation of the object's hashcode.
Hashcodes are an advanced Java concept and are used to provide a quick
integer representation for an object, which can be used as a quick check to
see if two objects are equal (they have the same hashcode). Again, the way
a hashcode is calculated can be extended by the programmer. If this is not
done, then the hashcode corresponds to the internal address of the object
in memory, although the particular default behavior may vary from one JVM
implementation to another.
Finally, you might be wondering what happens when you try to access an object's
field (instance variable) when an object was not created first, such as done here:
Book book = null;
System.out.println("Now, book title equals: "+book.title);
Eclipse will allow you to execute this code, but the program will quickly crash
with the following message:
Exception in thread "main" java.lang.NullPointerException
at Book.main(Book.java:XX)
Not surprising, because accessing a variable of something that doesn't
exist is sure to give problems. In this code sample, it's easy to see where
the problem lies (Eclipse will even put up a warning regarding this foolish
behavior), but in larger programs, it is a common pattern for methods to
create objects, or return null in case something failed. When this object is
then accessed (or passed on to another method, perhaps) without explicitly
checking for null , a NullPointerException error will pop up as soon as
you try to access a variable or method of this object, as the following code
sample illustrates:
Book giveMeABook() {
//return new Book(); --> Sorry, no topics available for now
return null; // Return null instead
}
continues
Search WWH ::




Custom Search