What will happen when following code is executed in Java?:

((A)null).x();

The obvious answer is that java.lang.NullPointerException will be thrown. But amazingly it’s not always true! if x() is static method on class A then null is ignored and method x() is invoked. You don’t believe it? Try it Yourself:

public class A {
    public static void main(String[] args) {
        ((A)null).x();
    }

    public static void x() {
        System.out.println("Hello World!");
    }
}

Personally I was sure that NPE will be thrown but after a while it seems reasonable – after all You don’t need actual instance of class to invoke its static method.

And yes, it’s actually useful!¬†When? Imagine static class with Your custom toolset:

public class Tools {
    public static void a() { System.out.println("a()"); }
    public static void b() { System.out.println("b()"); }
    public static void c() { System.out.println("c()"); }
    public static void d() { System.out.println("d()"); }
}

Tools.a();
Tools.b();
Tools.c();
Tools.d();

Almost every program has that kind of class (frequent examples are: String and Collection manipulation). Unfortunately it’s not very pretty code, it’s much more convenient to write and maintain:

public class Tools {
    public static Tools a() { System.out.println("a()"); return(null); }
    public static Tools b() { System.out.println("b()"); return(null); }
    public static Tools c() { System.out.println("c()"); return(null); }
    public static Tools d() { System.out.println("d()"); return(null); }
}
// ....
Tools.a().b().c().d();

Check if Your friends know that trick.