0

I have been learning about java byte-code recently, and i have been understanding most of it, but i am confused about how the local variable count for example is counted. I thought it would just be the total of the local variables, but this code generates 1 local variable when looking through the bytecode

public int testFail()
{
    return 1;
}

But i thought it should be zero local variables because no local variable are defined.

Additionally this method also generates one local variable but it has more local variables than the previous example.

Finally this method

public static int testFail(int a, int b)
{
    return a+b;
}

gnerates two local variable in the bytecode.

public static int testFail(int a)
{
    return a;
}
3

2 Answers 2

1

Non-static methods use a local variable slot for this. Another complication is that longs and doubles count as 2 each. Also, depending on your compiler and settings, you may not see a one-to-one mapping between local variables in the source code and local variables in the byte code. For example, if debug information is left out, the compiler may eliminate unnecessary local variables.

Edit:

I just remembered: compilers may also re-use local variable slots. For example, given this code:

public static void test() {
    for(int i = 0; i < 100; i++) {
        ...
    }
    for(int j = 0; j < 100; j++) {
    }
}

the same slot can be used for i and j because their scopes don't overlap.

Sign up to request clarification or add additional context in comments.

Comments

0

The reason the first one has a local variable is because it is a nonstatic method, so there is an implicit this parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.