We all know, that according to JLS7 p.4.12.5 every instance variable is initialized with default value. E.g. (1):
public class Test {
private Integer a; // == null
private int b; // == 0
private boolean c; // == false
}
But I always thought, that such class implementation (2):
public class Test {
private Integer a = null;
private int b = 0;
private boolean c = false;
}
is absolutely equal to example (1). I expected, that sophisticated Java compiler see that all these initialization values in (2) are redundant and omits them.
But suddenly for this two classes we have two different byte-code.
For example (1):
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
For example (2):
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: aconst_null
6: putfield #2; //Field a:Ljava/lang/Integer;
9: aload_0
10: iconst_0
11: putfield #3; //Field b:I
14: aload_0
15: iconst_0
16: putfield #4; //Field c:Z
19: return
The question is: Why? But this is so obvious thing to be optimized. What's the reason?
UPD: I use Java 7 1.7.0.11 x64, no special javac options
See Question&Answers more detail:os