My observation has been that javac may omit the store operations of unused variables if:
- The variables are marked as
final
and are initialized in the declaration;
- You do not compile with local variable debug info (
-g:vars
)
If you compile with -g:vars
, javac will keep the variables loads and stores in tact for debugging purposes. It does not appear to consider non-final variables as eligible for removal.
Test for yourself. My results with JDK 7 are below. The results were identical with a JDK 8 EAP.
Input:
class MyTest {
public static void main(String... args) {
int a = 1;
}
}
Output:
public static void main(java.lang.String... p0);
Flags: PUBLIC, STATIC, VARARGS
Code:
stack=1, locals=2, arguments=1
0: iconst_1
1: istore_1
2: return
Input:
class MyTest {
public static void main(String... args) {
final int a = 1;
}
}
Output:
public static void main(java.lang.String... p0);
Flags: PUBLIC, STATIC, VARARGS
Code:
stack=1, locals=2, arguments=1
0: return
As others have said, in either case I would expect the JIT optimizer to omit any unnecessary store operations.