This is based on a question from Bill Brogden's Exam Cram 1.2. I have changed nothing all I have provided is the necessary code to make the code fragment work. Given an input of null we are asked what would be the output? A. "Finally" is printed, false is returned. B. "Finally" is printed, NullPointerException" is thrown.
My answer was A, the apparent correct answer is B. REason given is:
A NullPointerException is thrown and is not caught in the method so the rest of method is not reached.
I put the above code into my compiler, because I was not convinced. To my way of thinking & question I have answered, if a catch block catches an exception & provides even a totally empty block the exception is considered caught. The catch block need not do any more than catch the exception. So when I run the code the program acted as I suspected it would. So let me first say that the Bill Brogden Exam Cram 1.2 is a great book, I have got a lot out of it so far. The reason I am posting this thread is not to be a smart arse but I would like your opinion whether I have got this right or not? If I am wrong then please fill me in. Thanks, Dave.
Hi Dave As Megan pointed out. null and "null" are two very different things. The first null means that the String object(in this case) does not contain anything and the second one means that it contains the value null. So in you use : System.out.println(w.aMethod(null)); You will get the answer mentioned as the correct answer. This is because "null" is not a number and a NumberFormatException will thrown but null does not contain anything so a NullPointerException will be thrown. [ June 03, 2003: Message edited by: Anupam Sinha ]
Wouldn't the output of this be Bad number is null Finally false
Joined: Apr 13, 2003
Hi Ryan In case "null" a string value is supplied then what you have said would be the output but in case null string, String that has not been assigned any value is used then option b in the first post is the answer.
Joined: Apr 16, 2003
Anupam Thank you. I should have been more specific in my post. What I wanted to say was with the way original question was coded ("null") the output would be.... Bad number is null Finally false
I was just confused that the line Bad number is null was not included in the answer.