简体   繁体   中英

Local Variable access in java

Java uses stack to store local variable.

看局部变量栈的图片

So, how java access local variables. Suppose I want to access the variable 'b', will it first pop the 'd' and 'c' variable to access it? If not how it is storing in stack and access when a programmer have to access local variable?

public class Solution {  
 public static void main(String args[]){  
    int a = 5;
    int b = 8;
    int c = 3;
    int d = c*3;
    System.out.println("Testing c "+c);
    System.out.println("Testing b "+b);
    System.out.println("Testing d "+d);
 }
}

Java uses stack to store local variable.

This is more or less incorrect.

Java in bytecode form is a combination of stacks and accessible variables. Yes, there is a stack, but there is also a small variable storage system, and most local variables end up in this system instead; bytecode can be generated to put a variable in a slot, and load a variable from a slot, without having to continuously push and pop all things 'on top' first.

Here's a trivial example; take java code:

public static void test() {
    Test t = new Test();
    System.out.println(t.a + t.b);
}

class Test {
    int a, b;
}

turns into this bytecode:

meta: stack=3, locals=2    ; [1]
INVOKESPECIAL #9           ; [2] 'new Test() -> result on stack'
stack now: instance of Test
ASTORE_1                   ; Pop stack and put result in 'slot 1'
stack now: empty.
GETSTATIC #10              ; Read field 'System.out' -> result on stack.
stack now: Sysout
ALOAD_1                    ; Copy 'slot 1' onto stack.
stack now: instance of Test, Sysout.
GETFIELD #16               ; Consume top of stack, read a field, put that on stack.
stack now: int (t.a), Sysout.
ALOAD_1
stack now: instance of Test, t.a, Sysout.
GETFIELD #20
stack now: t.b, t.a, Sysout.
IADD                       ; this has no params, it's all stack based.
stack now: the sum of t.a+t.b, Sysout.
INVOKEVIRTUAL #23          ; the println method
stack now: empty (the invokevirtual consumed it all).

notes on the above:

[1] in bytecode, the largest the stack will ever be, and the most of those 'local vars' we ever need is tracked. You can see this with javap.

[2] There is a constant pool. The 'index' into the constant pool containing, for example, a full method reference (so fully qualified class name + method name + method's signature) is part of the bytecode for things like 'invoke this constructor', 'read this field', etc. The #x marks in javap output are references to this constant pool.

For your snippet, I invite you to do the same thing I did: Write it up in a really simple java file, compile it, then run javap -c -private MyClass and have a look!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM