jdeveloper voice

Saturday, July 01, 2006

java hacks

When I was preparing to the Sun Certifed Java Programmer (the official name is "Sun Certified Programmer for the Java 2 Platform 1.4") exam I came across many tricky questions. Let's look at the following:


class Dog {
public static String sayHello() {
return "Whow...";
}
}

public class DogTest {
public static void main(String[] args) {
Dog dog = null;
System.out.println(dog.sayHello());
}
}


What is the output?

Everything goes fine and the "Whow..." will be printed. The NullPointerException won't occur. The key is the sayHello() static modifier.

Static methods are linked at compile time as opposed to the runtime linking of instance methods. Compiler doesn't use the value of reference variable at all in this situation. It uses the type of the reference variable only for the purpose of compile time linking.