5

I've stumbled across some pretty weird code that I'm surprised doesn't cause an error

public class WeirdCode {

    public static int fooField = 42;

    public WeirdCode getFoo(){
        return null; 
    } 
    public static void main(String args[]) {
        WeirdCode foo = new WeirdCode();
        System.out.println(foo.getFoo().fooField); 
    }
}

Surprisingly, it prints out 42! Can anyone explain?

Michael
  • 2,673
  • 1
  • 16
  • 27
  • 2
    What did you expect it'd return? – Reut Sharabani Jun 27 '15 at 01:40
  • 4
    @ReutSharabani I thought it would throw a NullPointerException – Michael Jun 27 '15 at 01:42
  • 4
    I think the downvoters didn't really read the code all the way through. This is not a bad question. I certainly thought it was going to throw. Thanks for allowing me to learn something new. +1 – sstan Jun 27 '15 at 01:44
  • @sstan Thanks, I'm glad we both learned something new then – Michael Jun 27 '15 at 01:45
  • 1
    possible duplicate of [How come invoking a (static) method on a null reference doesn't throw NullPointerException?](http://stackoverflow.com/questions/3293353/how-come-invoking-a-static-method-on-a-null-reference-doesnt-throw-nullpointe) – Reut Sharabani Jun 27 '15 at 01:56
  • @Michael I actually thought about it again after reading the explanation. – Reut Sharabani Jun 27 '15 at 01:56

1 Answers1

13

References to static members of a class are resolved at compile-time. The compiler doesn't care what the value of the expression is, just its type, and so a ((WeirdCode) null).fooField just resolves to WeirdCode.fooField like anything else.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152