Do uninitialized primitive instance variables use memory?

前端 未结 6 1913
庸人自扰
庸人自扰 2020-12-14 14:37

In Java, does it cost memory to declare a class level instance variable without initializing it?
For example: Does int i; use any memory if I don\'t initial

6条回答
  •  难免孤独
    2020-12-14 14:58

    The original question talks about class level variables and the answer is that they do use space, but it's interesting to look at method scoped ones too.

    Let's take a small example:

    public class MemTest {
        public void doSomething() {
            long i = 0;  // Line 3
            if(System.currentTimeMillis() > 0) {
                i = System.currentTimeMillis();
                System.out.println(i);
            }
            System.out.println(i);
        }
    }
    

    If we look at the bytecode generated:

      L0
        LINENUMBER 3 L0
        LCONST_0
        LSTORE 1
    

    Ok, as expected we assign a value at line 3 in the code, now if we change line 3 to (and remove the second println due to a compiler error):

    long i; // Line 3
    

    ... and check the bytecode then nothing is generated for line 3. So, the answer is that no memory is used at this point. In fact, the LSTORE occurs only on line 5 when we assign to the variable. So, declaring an unassigned method variable does not use any memory and, in fact, doesn't generate any bytecode. It's equivalent to making the declaration where you first assign to it.

提交回复
热议问题