wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Wow, never quite realized this before... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Wow, never quite realized this before..." Watch "Wow, never quite realized this before..." New topic
Author

Wow, never quite realized this before...

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
This isn't a real test question, but it could easily be.

Assuming the following method is inside a class, and everything compiles nicely, what will happen when line #12 is executed?

(A) A java.lang.NullPointerException will definitely be thrown
(B) A java.lang.NullPointerException will definitely not be thrown
(C) Impossible to determine from the given code.


[code]
10. public void foo() {
11. MyTest test = null;
12. test.someMethod();
13. }
[code]

The answer is (C) because the method could be static. Wonder how many people would be caught by this.
Arvind Sampath
Ranch Hand

Joined: May 11, 2005
Posts: 144
Nice Observation. Pls do post these kind of questions in the SCJP forum, so that the exam takers will be benefitted.

Cheers
Arvind
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I would be caught by it.

Fortunately, Eclipse can flag such code with a warning, and a quick fix to change the offending line to

MyTest.someMethod();



The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Wow, never quite realized this before...