Joker
Joker

Reputation: 11146

Method invocation on NULL works fine - Expecting NPE

I am able to invoke the greet method on null, Here i am expecting NPE as we can not invoke method on null from language specification JLS-15.12.

But here i am getting hello world

    public class Test{
    public static void greet() {
        System.out.println("Hello world!");
    }

    public static void main(String[] args) {
        ((Test) null).greet();
    }
}

Can some help me why I am getting hello world instead of NPE

Upvotes: 0

Views: 51

Answers (1)

TheLostMind
TheLostMind

Reputation: 36304

The compiler replaces your call with a static invocation. If you inspect your bytecode using javap -v className, you will see it.

stack=0, locals=1, args_size=1
         0: invokestatic  #31                 // Method greet:()V
         3: return

The compiler understands that you are needlessly using a complex way to call your method and reduces it to a basic static call. Static methods are meant to be called in a static context and not in an instance context, any good IDE will ask you to change your existing code.

Even if you do new Sample().greet();, the compiler does the same optimization.

Upvotes: 2

Related Questions