× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

In Java, what exactly constitutes as "initializing a local variable"?

James Jensen
Feb 10, 2015
<p>A local variable can be considered to be "initialized" if the compiler can easily deduce that every possible code path will lead through a path where the value has been set.</p> <ul> <li><code>if(true)</code> can be determined to always run.</li> <li><code>if(false)</code> can be determined to never run.</li> <li><code>if/else</code> can be determined to run at least one of the branches, so you must assign the variable in each branch if you want it to be guaranteed initialized. Same principle applies for <code>if/else if/.../else</code></li> <li><code>switch</code> statements will either run one of the possible <code>case</code>s, or will hit the <code>default</code> case, so if you assign the variable in all of these places then it can be guaranteed initialized.</li> </ul> <p>The Java compiler doesn't bother checking all the possible values of each variable at various points in the method when making this determination, because variables are <em>variable</em>--they can change. However, if values can be considered <em>constant</em> then it can safely assume they won't change. </p> <p>For example, the compiler doesn't care if you assign a variable and never change it in your code:</p> <pre><code>boolean val = true; if(val) { b = 5; } </code></pre> <p>Debuggers and things make it possible for you to change the value of <code>val</code> on-the-fly, so the compiler doesn't make any assumptions here. However, if you make <code>val</code> <em>constant</em>, by declaring it <code>final</code> and initializing it with a constant or literal value, then the compiler will treat it exactly the same as if you'd used the constant value in code.</p> <pre><code>final boolean val = true; if(val) { // Same as if you'd said `if(true)` b = 5; } </code></pre> <p>Such constants can be chained, as well, and the compiler will simplify them to their constant values rather than maintaining the longer expressions and operators:</p> <pre><code>final int five = 5; final int four = five - 1; // Same as `four = 5 - 1`, or `four = 4` final boolean val = five &gt; four; if(val) { // Same as `if(5 &gt; 4)`, or `if(true)` b = 5; } </code></pre> <p>For further reading, check out the <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-16.html" rel="nofollow">Java Specs</a>. (Hat tip to Radiodef for finding the right section.)</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23207471/In%20Java,%20what%20exactly%20constitutes%20as%20%22initializing%20a%20local%20variable%22?/23207578">Stack Overflow</a>.</p>
comments powered by Disqus