Static Fields Through null Variables

| 3 Comments

This surpised me. The following program does not throw a NullPointerException

public class StaticFieldThroughNull {
    public static void main(String[] args) {
	Double d = null;
	System.out.println(d.MAX_VALUE);
    }
}

This really is supposed to work this way. See the JLS.

Check out the example at the end of the section of the spec linked above. Its even more surprising than mine, because it uses a method that returns null rather than a null variable.

3 Comments

This bug was fixed in 1.4.1...

http://developer.java.sun.com/developer/bugParade/bugs/4449316.html

From my reading of the but report cited above, it sounds like it is a related bug, and that they almost changed the behavior I pointed out, but then realized that they should not chnage it.

It would be a bug if the code I included in the blog entry did actually throw a NullPointerException. I'm not sure what the behavior was prior to Java 1.4.1.

What I forgot to make clear in my post was that since we're examining a static field, it is only the type of the variable that matters, not its value. That is why the static field can be accessed through the null value.

FWIW, I'd be having a chat to any of your developers that routinely access static members through instance variables, null or not. They're static for a reason :-)

Books

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

Completely updated for Ajax and Web 2.0

"A must-have reference"
Brendan Eich,
creator of JavaScript

The classic Java quick-reference

Advertising

Pages

Hosted By

Powered by Movable Type 4.21-en