0

I have the following code and I wonder, how many times (and on which lines) JVM will allocate memory for ints:

public final class Test {                            // LINE 1
    public static void main(final String[] args) {   // LINE 2
        a(1);                                        // LINE 3
    }                                                // LINE 4
                                                     // LINE 5
    private static void a(final int x) {             // LINE 6
        b(x);                                        // LINE 7
    }                                                // LINE 8
                                                     // LINE 9
    private static void b(final int x) {             // LINE 10
        c(x);                                        // LINE 11
    }                                                // LINE 12
                                                     // LINE 13
    private static void c(final int x) {             // LINE 14
        if (x == 0)                                  // LINE 15
            return;                                  // LINE 16
                                                     // LINE 17
        d(x);                                        // LINE 18
    }                                                // LINE 19
                                                     // LINE 20
    private static void d(int x) {                   // LINE 21
        c(x - 1);                                    // LINE 22
        c(--x);                                      // LINE 23
    }                                                // LINE 24
}                                                    // LINE 25
Brongs Gaming
  • 59
  • 1
  • 8
  • 1
    Does this answer your question? [Where does the JVM store primitive variables?](https://stackoverflow.com/questions/3698078/where-does-the-jvm-store-primitive-variables) – Krzysztof Kaszkowiak Jan 25 '21 at 15:20

1 Answers1

2

More or less: Nowhere.

line 3: '1' is a constant. This constant is in memory, but in the part where bytecode is loaded (hey, code needs to be someplace, too!). It's not in memory as a '1', it's in memory as the bytecode ICONST_1 (which is a single byte opcode, for what it is worth). Compile it and run javap -c on the class file to see this.

line 6: A parameter is passed on the stack. local variables also exist on the stack. For this and all further lines, everything occurs on the stack. All threads get 1 stack and each stack is a set size (which size? Depends; you can control it when you start a VM using the -Xss parameter.

In this code snippet, the heap is entirely unused.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72