wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why the program hangs up at runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why the program hangs up at runtime" Watch "Why the program hangs up at runtime" New topic
Author

Why the program hangs up at runtime

Divyya Joshi
Ranch Hand

Joined: Jul 15, 2010
Posts: 102
The following code in from exercise of K&B . The answer shows that it might throw Nullpointer exception as well as program might hang without ever completing.

I don't understand why it will throw Null Pointer Exception. All though answer explains since Integer i is not initialized it.. But according to my knowledge instance variables are assigned value '0' .

Here's the code:



Kindly anyone explain this to me..
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18675
    
    8

Divyya Joshi wrote:But according to my knowledge instance variables are assigned value '0' .


This must be today's catch-phrase: "According To My Knowledge". I seem to be spending my whole morning pointing out that people's "knowledge" is incorrect.

And yes, it's incorrect. Instance variables are only assigned value '0' if they are of type char and the programmer explicitly assigns that value.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

Paul might be slightly pickily distinguishing between '0' and 0 (), but he's right that this is not what happens. Reference member variables get initialised to null if a value isn't specified, and Integer is a reference variable.
Divyya Joshi
Ranch Hand

Joined: Jul 15, 2010
Posts: 102
Thanks Paul and Matthew
Is it that the program would have run fine if instead of Integer we had int as instance variable?
Anjali Vaidya
Ranch Hand

Joined: Jan 25, 2011
Posts: 40

Is it that the program would have run fine if instead of Integer we had int as instance variable?


yes! it runs fine if you use int because instance variables of type "int" are given 0 as their default value.
Glen Iris
Ranch Hand

Joined: Jul 13, 2011
Posts: 164

What might cause this program to hang?

Is it that Case 0: might never get invoked?

Is there any other reason?


OCPJP 6, OCMJD
Glen Iris
Ranch Hand

Joined: Jul 13, 2011
Posts: 164

Glen Iris wrote:What might cause this program to hang?

Is it that Case 0: might never get invoked?

Is there any other reason ?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why the program hangs up at runtime