×
Namespaces

Variants
Actions
Revision as of 06:03, 29 July 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Initializing local variables in Java

From Nokia Developer Wiki
Jump to: navigation, search

This article discusses the commonly accepted rule that you should always initialize a local variable where it is declared. While this is generally a good rule, there are situations where dogmatically following it can reduce code quality.

Article Metadata
Article
Created: grahamhughes (26 Jun 2010)
Last edited: hamishwillee (29 Jul 2013)

How Java and C are Different

The "always initialize" rule is, to some extent, a hang-over from C and C++, where it is also a good rule. But the C and Java are quite different (in spite of the similarity in appearance). Importantly:

  • In Java, it is a fixed rule that you may not read the value from a local variable unless the compiler can prove that the variable will have been initialized. Otherwise, the code will not compile. This is the "definite assignment" rule.
  • In C (and C++), you can read the value from a local variable any time you like. Its value will be whatever was lying around in memory at the time - which will depend on what that memory has been used for most recently. Depending on the rest of the program, this might be a consistent value, or it might be quite random. Either way, you have no control.

A good C compiler can warn you if you use variables without initializing them first - basically implementing Java's definite assignment rule. Smart C programmers switch this warning on, and probably set it to "report warnings as errors", so that they get the same protection from random memory values as Java programmers. Some C programmers are not smart, and some smart C programmers have to maintain other programmers' "works of genius" and have to switch off compiler warnings (or spend months getting the code up to scratch - months that their schedule probably doesn't allow).

In the absence of help from the compiler, initializing variables always becomes a best-practice. Even if the value you initialize to will later cause an error, at least it will cause a consistent error, not random ones.

In Java, definite assignment protects us from random errors caused by random values.

Not Initializing

Sometimes, leaving a variable uninitialized can help you.

Quite often, we want to assign one of a number of values to a variable, based on some conditions. This might be a switch, or an "if... else if..." chain.

public int root(int value) {
int root = 0;
boolean square;
 
switch (value) {
case 1:
root = 1;
square = true;
break;
case 2:
root = 1;
square = false;
break;
case 3:
root = 1;
square = false;
break;
case 4:
root = 2;
square = true;
break;
case 5:
root = 2;
square = false;
break;
case 6:
root = 2;
square = false;
break;
case 7:
square = false;
break;
case 8:
root = 2;
square = false;
break;
case 9:
root = 3;
square = true;
break;
default:
throw new IllegalArgumentException("cannot process " + value);
}
 
return root;
}

Bear in mind that, in reality, the logic might be more complex, and there might be more variables to initialize, making my deliberate mistake harder to spot.

You spotted it, right? I didn't initialize "root" for the case of 7. Sadly, because I initialized root to zero when I declared it, this code compiles happily. When it runs, it sometimes behaves a bit strangely. Perhaps, sometimes, things on the screen get drawn in slightly the wrong place. How long to you think it will take me to go from seeing this graphical anomaly, to working out that I missed out "root = 2" from this method?

On the other hand, if I'd just written:

int root;   // no initial value

then the compiler would have refused to compile the code. Eclipse (or whatever IDE) would have underlined "return root" in red for me, telling me immediately that I've made a mistake. That's going to save me hours of debugging. (Or, save me releasing a broken piece of software to my customer.)

Conclusion

Initialize variables as soon as possible after declaring them, ideally when you declare them. But: initialize them when you have something useful to initialize them to.

If you habitually initialize variable to zero or null, you are likely to spend hours tracking down NullPointerExceptions and ArithmeticExceptions, days tracking down unusual behaviors. Worse, you might release broken code to the people who are paying you, and damage your credibility as a professional developer.

This page was last modified on 29 July 2013, at 06:03.
191 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×