permaculture playing cards*
The moose likes Java in General and the fly likes Doubt in K&B SCJP 5 Book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Doubt in K&B SCJP 5 Book" Watch "Doubt in K&B SCJP 5 Book" New topic
Author

Doubt in K&B SCJP 5 Book

Deepak Kumar
Ranch Hand

Joined: Nov 05, 2007
Posts: 62
Hi All,

I have doubt regarding the example from K&B SCJP5 Book page# 94.
Is it a mistake?

The code snippet given as from K&B

1.public class Horse extends Animal{
2. private Halter myHalter;
3. public void tie(LeadRope rope){
4. myHalter.tie(rope);// NullPointerException
5. }
6. }

7.public class Halter{
8. public void tie(LeadRope arope){
9. // Do the actual tie work
10. }
11.}



given that the code compiles fine, but at line# 4 it throws a NullPointerException. So I think line# 2 must changed to private Halter myHalter = new Halter();


correct me If I am wrong?


Thanks,
Deepak
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

So I think line# 2 must changed to private Halter myHalter = new Halter();


I believe that you are right. Because the variable myHalter is defined within the scope of a class, it defaults to null. Trying to dereference myHalter with the expression...

myHalter.tie()

...is trying to dereference a null object. The exception that is thrown is actually a good thing. In older languages (such as Pascal, C, and C++) if you tried to use an object reference variable that was not initialized, the value would be whatever is left on the stack and you would get indeterminate results.

The nullPointerException here in Java saves you time because it tells you exactly which line of code is the problem.

So, why doesn't the compiler catch the problem?

click here
[ January 11, 2008: Message edited by: Kaydell Leavitt ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38509
    
  23
The compiler never finds whether an object has been instantiated or not. That is beyond it. The idea behind the NullPointerException is that it crashes the application rather than allow it to produce undefined or unpredictable results. Even though there are cases which don't follow this rule (eg NumberFormatException) most unchecked Exceptions represent a mistake in the code. Look at the Java Tutorial.

What you need to do is to instantiate the object, which I think is best done in a constructor. Whenever you declare a field, you go to the constructor and make sure to instantiate that field there.
Deepak Kumar
Ranch Hand

Joined: Nov 05, 2007
Posts: 62
Thank You very much.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt in K&B SCJP 5 Book