I'd like to start a series of Java brain teasers which would ask a question about a tricky Java code excerpt. I will probably publish one/two teasers a week and they could serve as thinking material for preparing for the SCJP exam. After a couple days, I will provide the right answer as well as a pointer to the correct section in the JLS handling the subject. I hope you'll find this exercise useful. As an example, please find below the first one:
What output is printed out when the following code is run?
[ October 27, 2006: Message edited by: Valentin Crettaz ]
Good one Valentin. Since the method 'greet' is static, output will be "Hello world", if we remove the 'static' keyword, we will get a NullPointerException. [ October 27, 2006: Message edited by: Rajesh Kadle ]
Java language also allows you to use an object reference to access a static member. When you access a static member on an object reference, what the value of the object reference is (point to an instance or null) ignored, only the type of the object reference matters.
Joined: Aug 15, 2006
Java language also allows you to use an object reference to access a static member.
Is there any legitimate reason for writing code that uses this syntax? (Other than for writing tricky Java brainteasers, of course!) At first glance, it seems that it would always be clearer to access static members using the class name.
Joined: Feb 02, 2006
This is bad or at least poor form because it creates the impression that some instance variables in the object are used, but this isn't the case. It's best practice to always invoke static member using the class name rather then an object reference of the class. [ October 27, 2006: Message edited by: wise owen ]
Joined: Aug 26, 2001
All right, guys, thanks for participating !
The correct answer was that "Hello World!" is getting printed out (without the quotes ).
As wise owen correctly pointed out, it is bad practice to invoke a static method on a reference variable. As a good practice, the declaring class name should be used instead. Also, the fact that the class was called Null is not a problem as such.