Beware of mistaken field redeclares

Beware of this simple mistake, which can be hard to track down: if a field is mistakenly redeclared within the body of a method, then the field is not being referenced, but rather a temporary local variable with the same name.

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.


public final class MistakenRedeclare {

  public static void main(String... aArguments ) {
    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;
    //this style may help to eliminate such errors:
    //this.fName = aName;

  public String getName(){
    return fName;


  private String fName;

Example run of this class:

>java -cp . MistakenRedeclare
Exception in thread "main" java.lang.NullPointerException
        at MistakenRedeclare.main(

See Also :
Naming conventions