Do unused local variables in a method acquire memory in JVM?

前端 未结 5 774
感情败类
感情败类 2020-12-15 04:17

I came across this post in SO Do uninitialized primitive instance variables use memory?

It states \"In Java, does it cost memory to declare a class level instance va

5条回答
  •  攒了一身酷
    2020-12-15 04:38

    Class level / Instance level variables will be initialized to their default values automatically. So, yes, they will occupy some space when a class is initialized / instance created respectively.

    As far as method local variables are concerned, No, if they are just declared but not initialized, then they will not use any space, they are as good as ignored by the compiler..

    If your code was this :

    public static void main(String[] args) {
        int i;  // ignored
        int j = 5;
        String s = "abc";
        String sNull; // ignored
    }
    

    Byte code :

      LocalVariableTable:
            Start  Length  Slot  Name   Signature
                0       6     0  args   [Ljava/lang/String;
                2       4     2     j   I
                5       1     3     s   Ljava/lang/String;
       }
    

提交回复
热议问题