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;
}
Popgalop
  • 737
  • 2
  • 9
  • 26
  • 2
    both of the method above are the same. –  Jun 28 '13 at 13:01
  • sorry i fixed that i posted both methods – Popgalop Jun 28 '13 at 13:03
  • 1
    Have a look at these links http://arhipov.blogspot.com/2011/01/java-bytecode-fundamentals.html and http://zeroturnaround.com/rebellabs/java-bytecode-fundamentals-using-objects-and-calling-methods/#!/ –  Jun 28 '13 at 13:09

2 Answers2

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.

Adam Crume
  • 15,614
  • 8
  • 46
  • 50
0

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

Antimony
  • 37,781
  • 10
  • 100
  • 107