Note that there are some explanatory texts on larger screens.

plurals
  1. POCan a compliant Java compiler optimize this code?
    text
    copied!<p>I was teaching an introductory programming course today and was walking through some simple code involving variable assignments in Java. The point of the code wasn't to show off anything particular exciting, but mostly to make sure students understood variable assignment statements.</p> <p>I had the following method up on the board and was tracing through it one line at a time:</p> <pre><code>private void simpleMethod() { int myInt = 137; myInt = 42; myInt = myInt + 1; /* ... code using myInt ... */ } </code></pre> <p>A student asked me whether <code>myInt</code> would ever actually hold the values 137 and 42 when the program ran, or if it would just jump straight to holding 43. I told the student that the code would execute each line in turn, so the variable would actually hold these intermediate values.</p> <p>Honestly, though, I wasn't sure what bytecode <code>javac</code> would emit (completely ignoring the optimizations done by the JVM). Is <code>javac</code> (or any Java compiler) legally allowed to optimize the silly assignment statements away and to instead just directly initialize <code>myInt</code> to 43?</p> <p>According to <code>javap</code>, on my system, the above code compiled with <code>javac</code> produces</p> <pre><code> 0: sipush 137 3: istore_1 4: bipush 42 6: istore_1 7: iload_1 8: iconst_1 9: iadd 10: istore_1 11: return </code></pre> <p>So there is no optimization going on here. My question, though, is whether it's <em>legal</em> to optimize this or not, so this doesn't resolve anything.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload