Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 variable without initializing it? For example: Does int i; use any memory if I don't initialize it with i = 5;?"

My question is what in case of local variables, say i have a method foo()

public int foo(){

  int x;

//Write code which does not use/initialize x
}

Will the local variable x occupy memory?

Edit

Jon's Answer is

UPDATE: Doing a bit more research on this, I find this page which suggests to me that, although the compiled bytecode implies that space is allocated for x, it may indeed be optimized away by the jvm. Unfortunately, I find no complete description of the optimizations performed. Particularly, the JVM documentation chapter on compiling does not mention removing unused variables from the stack. So, barring further discoveries, my answer would be that it's implementation-dependent, but it seems like the sort of optimization that any self-respecting compiler would perform. Notice too that it doesn't matter that much that this is a local variable rather than a field - in fact, local variables are the ones most likely to be optimized away, since they are the easiest to analyze and eliminate. (precisely because they are local)

Let us see if can find more evidences which supports this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...