Naming conventions
A common symptom of this problem is that a stack trace indicates that a
field is null
, but a cursory examination of the code makes it
seem as if the field has been correctly initialized.
Naming conventions can reduce the frequency of this error, but they cannot eliminate it.
Example
public final class MistakenRedeclare { public static void main(String... aArgs) { MistakenRedeclare mistake = new MistakenRedeclare("blah"); //Throws NullPointerException, since the return value of //getName is null. System.out.println("Length of name: " + mistake.getName().length()); } public MistakenRedeclare(String aName) { //Oops! Setting a local variable, not the field! String fName = aName; //should really be: //fName = aName; // //if you qualify references with the 'this' keyword, //then you don't need a conventional 'f' and 'a' //prefixes (to distinguish field versus argument) //this.name = name; } public String getName(){ return fName; } //..elided // PRIVATE private String fName; }
>java -cp . MistakenRedeclare
Exception in thread "main" java.lang.NullPointerException
at MistakenRedeclare.main(MistakenRedeclare.java:7)