Why must local variables, including primitives, always be initialized in Java?

JavaVariablesPrimitive Types

Java Problem Overview


Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?

Java Solutions


Solution 1 - Java

Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.

Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)

There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.

Solution 2 - Java

In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:

Object o;
if (<some boolean condition>)
  o = <some value>;
else
  o = <some other value>;
System.out.println(o);

An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.

This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.

Solution 3 - Java

Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:

int x;  // Valid
int y;
println("y=" + y);  // Not valid since y's value has never been assigned

Solution 4 - Java

Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.

Solution 5 - Java

Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.

Solution 6 - Java

In practice all variables need to be initialized before using them.

I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).

Solution 7 - Java

It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.

And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc

Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.

So when the stack will end local method's value will also get destroyed therefore: 1] They are supposed to be initialized explicitly (when we use them) 2] They should not be initialized implicitly (by null,0 or false) like instance variables

Solution 8 - Java

Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGouravView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaSvenView Answer on Stackoverflow
Solution 3 - JavaSteve KuoView Answer on Stackoverflow
Solution 4 - JavaquosooView Answer on Stackoverflow
Solution 5 - JavamonksyView Answer on Stackoverflow
Solution 6 - JavaJames CronenView Answer on Stackoverflow
Solution 7 - JavaShashank BodkheView Answer on Stackoverflow
Solution 8 - Javaudoh unyimeView Answer on Stackoverflow