I came across this post in SO Do uninitialized primitive instance variables use memory?
It states \"In Java, does it cost memory to declare a class level instance va
Expanding slightly on the testcase from @JonKiparsky:
public class StackSlotTest {
public int bar(){
int a;
a = 5;
System.out.println("foo");
return a;
}
public int foo(){
int x;
int a;
a = 5;
System.out.println("foo");
return a;
}
}
I added the variable a to both methods, and added a set and use of it in both.
public int bar();
Code:
0: iconst_5
1: istore_1
2: getstatic #2 // Field java/lang/System.out:Ljava/
io/PrintStream;
5: ldc #3 // String foo
7: invokevirtual #4 // Method java/io/PrintStream.printl
n:(Ljava/lang/String;)V
10: iload_1
11: ireturn
Above you see that the iload_1 bytecode loads the value of a to be returned. The second stack slot is referenced. (The first is the this pointer.)
public int foo();
Code:
0: iconst_5
1: istore_2
2: getstatic #2 // Field java/lang/System.out:Ljava/
io/PrintStream;
5: ldc #3 // String foo
7: invokevirtual #4 // Method java/io/PrintStream.printl
n:(Ljava/lang/String;)V
10: iload_2
11: ireturn
In this case the value of a is loaded with iload_2, to access the third slot, because the second slot is occupied (sort of) by the (totally unused) variable x.