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.
I had the following method up on the board and was tracing through it one line at a time:
private void simpleMethod() {
int myInt = 137;
myInt = 42;
myInt = myInt + 1;
/* ... code using myInt ... */
}
A student asked me whether myInt
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.
Honestly, though, I wasn't sure what bytecode javac
would emit (completely ignoring the optimizations done by the JVM). Is javac
(or any Java compiler) legally allowed to optimize the silly assignment statements away and to instead just directly initialize myInt
to 43?
According to javap
, on my system, the above code compiled with javac
produces
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
So there is no optimization going on here. My question, though, is whether it's legal to optimize this or not, so this doesn't resolve anything.