| 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: 13842
|
|
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: 2686
|
|
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: 69
|
|
What might cause this program to hang?
Is it that Case 0: might never get invoked?
Is there any other reason?
|
OCPJP 6
|
 |
Glen Iris
Ranch Hand
Joined: Jul 13, 2011
Posts: 69
|
|
Glen Iris wrote:What might cause this program to hang?
Is it that Case 0: might never get invoked?
Is there any other reason ?
|
 |
 |
|
|
subject: Why the program hangs up at runtime
|
|
|