3

Guys I recently saw some piece of code, and have not any idea why it works?

 public class Test1{

    static Test1 test(){
        System.out.println("test");
        return null;
    }

    static void print(){
        System.out.println("print");
    }

    public static void main(String...strings){
        test().print();
    }

}
user207421
  • 305,947
  • 44
  • 307
  • 483
Kirill Solokhov
  • 400
  • 4
  • 16

1 Answers1

2

Look closely, print() is a static method. This means it can be invoked without an instance of Test1. I.e. it can simply be called as:

Test.print();

The fact that the test() method returns null is irrelevant. In fact, if you're using a modern IDE it will probably have a warning on your invocation of test().print() warning you that you're trying to invoke a static method on an instance of an object.

There is no NullPointerException because the JVM is not trying to deference the object returned by test(). The JVM knows that it does not need to invoke a static method on an instance of an object.

If you want to know more about the underlying implementation, and the difference between invokespecial and invokestatic I'd suggest this question.

Community
  • 1
  • 1
jwa
  • 3,239
  • 2
  • 23
  • 54
  • 1
    I know this, but could you give more advanced explanation? Why we dont receive NPE? – Kirill Solokhov Nov 29 '13 at 22:33
  • 1
    @KirillSolokhov The JVM simply knows that it does not need to dereference the object when it's a static method. – jwa Nov 29 '13 at 22:35
  • @Kirill assume its not null, what would the compiler do? Use the declared class and call the static method. Talking to the actual instance is a waste of time so it doesn't bother. As a result of this the JVM doesn't even know that it's null – Richard Tingle Nov 29 '13 at 22:44